为什么箭头功能表现怪异?
问题描述:
考虑下面的代码:为什么箭头功能表现怪异?
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()中改变了。这本身就消除了“绑定”功能的一个用例。背后的原因是什么?
答
在箭头函数中,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?。
对于一个很好的解释,也请看看这个:http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan