为什么箭头功能表现得很奇怪?

时间:2017-01-02 07:28:31

标签: javascript ecmascript-6 arrow-functions

请考虑以下代码:

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"的一个用例。功能。它背后的原因是什么。

1 个答案:

答案 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?