gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:40:19 25 4
gpt4 key购买 nike

考虑以下代码:

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"

这是预期的,因为它仍然绑定(bind)“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”不会绑定(bind)到箭头函数。但是这里“foo”的上下文在 showName() 中发生了变化。这本身就删除了“绑定(bind)”功能的一个用例。背后的原因是什么。

最佳答案

在箭头函数中,this 是词法解析的,基本上就像任何其他变量一样,例如像名称。函数如何调用并不重要,它的 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? .

关于javascript - 为什么箭头函数表现得很奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com