【问题标题】:Why arrow function is behaving weirdly?为什么箭头函数的行为很奇怪?
【发布时间】: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() 中发生了变化。这本身消除了“绑定”功能的一个用例。背后的原因是什么。

【问题讨论】:

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

在箭头函数内部,this 是在词法上解析的,基本上就像任何其他变量一样,例如喜欢name。不管函数是如何调用的,它的this值将在函数被创建时确定。

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


另见What does "this" refer to in arrow functions in ES6?Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

【讨论】:

  • 我不知道。我觉得值得谈论这个具体的例子。但我对此没有强烈的意见。
  • @mplungjan 我以前读过这个问题,但我认为这是一些具体的例子。即使您可以将变量分配给箭头函数,这将始终仅指向原始对象。这是新事物,所以我认为重复是不合适的。
猜你喜欢
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2019-09-06
  • 1970-01-01
  • 2023-01-07
  • 2019-12-19
相关资源
最近更新 更多