什么是 this:自动引用正在调用当前方法的"."前的对象。
this指向的三种情况
obj.fun() fun 中的 this->obj ,自动指向"."前的对象
new Fun() Fun 中的 this->正在创建的新对象,new 改变了函数内部的 this 指向,导致 this 指向实例化 new 的对象
fun() 和匿名函数自调 this 默认->window,函数内部的 this,this 默认是指向 window 的
回调函数中的this默认是指向window的,因为本质上是在函数内callback,并没有"."前的对象调用
如何解决: 1.如何解决:使用箭头函数 箭头函数中的 this:
函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象。
this 指向的固定化,并不是因为箭头函数内部有绑定 this 的机制,实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。正是因为它没有 this,所以也就不能用作构造函数。
2.也可使用bind永久绑定this
var Bob={
sname:"鲍勃",
friends:["Jack","Rose","Tom","Jerry"],
intr(){
this.friends.forEach(function(friend){
console.log(this.sname+"认识"+friend);
}.bind(this));
}
}
Bob.intr();
评论(0)