1. 程式人生 > >ES6箭頭函式修復ES5中this指向問題

ES6箭頭函式修復ES5中this指向問題

長期以來,ES5中this物件一直的指向一個令人頭痛的問題,在物件方法中使用此,必須非常小心例如:

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout(function(){
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}

var animal = new Animal()
animal.says('hi')  //undefined says hi

執行上面的程式碼會報錯,這是因為setTimeout中的this指向的是全域性物件。所以為了讓它能夠正確的執行,傳統的解決方法有兩種。

第一種是將this傳給self,再用self來指代this

 says(say){
     var self = this;
     setTimeout(function(){
         console.log(self.type + ' says ' + say)
     }, 1000)

第二種是用bind(this)

   says(say){
       setTimeout(function(){
           console.log(this.type + ' says ' + say)
       }.bind(this), 1000)

而用ES6中的箭頭函式就沒有這麼麻煩

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}
var animal = new Animal()
animal.says('hi')  //animal says hi

當我們使用箭頭函式時,函式體內的this物件,就是定義時

所在的物件,而不是使用時所在的物件。
並不是因為箭頭函式內部有繫結this的機制,實際原因是箭頭函式根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層程式碼塊的this