考慮下面的代碼:爲什麼箭頭功能表現怪異?
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()中改變了。這本身就消除了「綁定」功能的一個用例。背後的原因是什麼?
對於一個很好的解釋,也請看看這個:http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan