请考虑以下代码:
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"
我知道'这个'不会绑定箭头功能。但在这里" foo"在showName()中已更改。这本身就删除了" bind"的一个用例。功能。它背后的原因是什么。
答案 0 :(得分:4)
在箭头函数中,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?。