2017-01-02 93 views
1

考慮下面的代碼:爲什麼箭頭功能表現怪異?

function Person (name) { 
    this.name = name; 
    this.showName = function() { console.log(name, this.name);} 
} 

var foo = new Person('foo'); 

var bar = new Person('bar'); 

foo.showName = bar.showName; 

foo.showName(); // prints "bar foo" 

預計,因爲這仍然結合「富」。

箭頭功能

現在:

function Person (name) { 
    this.name = name; 
    this.showName =() => console.log(name, this.name); 
} 

var foo = new Person('foo'); 

var bar = new Person('bar'); 

foo.showName = bar.showName; 

foo.showName(); // prints "bar bar" 

我知道「這」不綁定到箭頭的功能。但是這裏的「foo」的上下文已經在showName()中改變了。這本身就消除了「綁定」功能的一個用例。背後的原因是什麼?

+0

對於一個很好的解釋,也請看看這個:http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan

回答

4

在箭頭函數中,this在詞法上是解決的,基本上和其他變量一樣,例如,像name。無論函數如何被調用,它的this值將在函數創建爲時確定。

因此,this裏面的bar.showName將始終引用由new Person('bar')創建的實例。


另請參閱What does "this" refer to in arrow functions in ES6?Arrow function vs function declaration/expressions: Are they equivalent/exchangeable?

+1

我不知道。我覺得值得談論這個具體的例子。但我對此沒有強烈的意見。 –

+1

@mplungjan我之前讀過這個問題,但我認爲這是一些具體的例子。即使您可以將變量分配給箭頭函數,並且這隻會始終指向原始對象。這是新東西,所以我認爲重複是不合適的。 – MSati

+0

重新打開並鏈接到http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan