天天看點

ES6 箭頭函數this指向問題

1.箭頭函數文法

var a = b => c
           

2.箭頭函數this

通過一個例子:

var obj={
        a:,
        func:()=>{
            //console.log(this);
            //Window
            console.log(this.a);
        },
        test:function(){
            //`console.log(this)`;
            //{a: , func: ƒ, test: ƒ}
            setTimeout(()=>{
             //console.log(this);
             //{a: , func: ƒ, test: ƒ}
             this.func();
             },);
        }
    }
    obj.test();
           

上面的代碼輸出結果為undefined。自上而下三次

console.log(this)

的傳回值 以此是 window、obj、obj。

關于箭頭函數,從阮一峰的ES6一書中可以總結出兩點:

  1. 箭頭函數是沒有this對象的。
  2. 箭頭函數的this,就是在定義箭頭函數時,函數所在的對象。

也就是說箭頭函數中的this實際上是将定義時函數所在對象中的this“拿過來了”。就像是一個全局變量可以在函數内部使用一樣,箭頭函數中的this就像這個全局變量。

當調用obj.test()時,this.func();的這個this就是test函數中的this。而test函數中的this指向的是在調用時的對象。這個對象就是obj。執行到func時, console.log(this.a);中的這個this是指向window的,window中沒有a這個變量,是以最後的結果是undefined。