【发布时间】:2017-01-02 07:28:31
【问题描述】:
考虑以下代码:
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"
这是预期的,因为它仍然绑定“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"
我知道“this”不绑定到箭头函数。但是这里“foo”的上下文在 showName() 中发生了变化。这本身消除了“绑定”功能的一个用例。背后的原因是什么。
【问题讨论】:
-
为了更好的解释,也看看这个:stackoverflow.com/questions/22939130/…
标签: javascript ecmascript-6 arrow-functions