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();  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM