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指向问题,我们先来看一个例子

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

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

猜你喜欢

转载自www.cnblogs.com/jiajialove/p/10779655.html