JS回调函数中的this指向(详细)

时间:2023-03-09 01:34:51
JS回调函数中的this指向(详细)

首先先说下正常的 this 指向问题

什么是 this:自动引用正在调用当前方法的.前的对象。

this指向的三种情况

1. obj.fun()     fun 中的 this->obj ,自动指向.前的对象

2. new Fun()   Fun 中的 this->正在创建的新对象,new 改变了函数内部的 this 指向,导致 this 指向实例化 new 的对象

3. fun() 和匿名函数自调    this 默认->window,函数内部的 this,this 默认是指向 window 的

再说回调函数中的 this 指向问题,我们先来看一个例子

 <script>
var Bob={
sname:"鲍勃",
friends:["Jack","Rose","Tom","Jerry"],
intr(){
this.friends.forEach(function(ele){
console.log(this.sname+"认识"+ele);
});
}
}
Bob.intr();
</script>

看结果:

undefined认识Jack
undefined认识Rose
undefined认识Tom
undefined认识Jerry

回调函数中的this默认是指向window的,因为本质上是在函数内callback,并没有.前的对象调用

如何解决:

使用箭头函数

 1<script>
2 var Bob={
3 sname:"鲍勃",
4 friends:["Jack","Rose","Tom","Jerry"],
5 intr(){
6 this.friends.forEach(ele=>{
7 console.log(this.sname+"认识"+ele);
8 });
9 }
10 }
11 Bob.intr();
12 </script>

结果是:

鲍勃认识Jack
鲍勃认识Rose
鲍勃认识Tom
鲍勃认识Jerry

可以看出箭头函数内的this自动指向了回调函数外层的 this 。

箭头函数中的 this:

  函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象。

  this 指向的固定化,并不是因为箭头函数内部有绑定 this 的机制,实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。正是因为它没有 this,所以也就不能用作构造函数。

也可使用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();