为什么箭头函数表现得很奇怪?

Why arrow function is behaving weirdly?

考虑以下代码:

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() 中发生了变化。这本身就删除了 "bind" 函数的一个用例。背后的原因是什么。

在箭头函数中,this 是词法解析的,基本上就像任何其他变量一样,例如喜欢 name。函数的调用方式无关紧要,它的 this 值将在函数 创建时确定 .

因此,bar.showName 中的 this 将始终引用由 new Person('bar') 创建的实例。


另见 and