考虑下面的代码:为什么箭头功能表现怪异?
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