js中this指向

2021-04-10  本文已影响0人  LuckySweet123

1.this总是指向函数的直接调用者
2.如果有new关键字,this指向new出来的那个对象
3.DOM事件中this指向目标元素
4.箭头函数中的this指向他所在函数级别的作用域


    let p1={name:'p1'}
     let p2={name:'p2'}
     let getName=function(){
         console.log(this,'函数')
     }
     getName()//window
     p1={
         ...p1,
         getName
     }
     p1.getName()//p1
    
     const Cat=function(name,age){
         this.name=name
         this.age=age
        console.log(this,'cat')//Cat
     }
     let c1=new Cat('mimi',2)

指向箭头函数定义时所处的对象,而不是箭头函数使用时所在的对象,默认使用父级的this..箭头函数中的this,首先从它的父级作用域中找,如果父级作用域还是箭头函数,再网上找,如此直至找到this的指向

var a={
    b:function(){
        console.log(this)
  },
    c:{d:()=>{
        console.log(console.log(this))
        }}
}

a.b()//a
a.c.d() //window
上一篇 下一篇

猜你喜欢

热点阅读