gpt4 book ai didi

javascript - 这。引用对象而不是窗口对象

转载 作者:行者123 更新时间:2023-11-29 18:42:33 26 4
gpt4 key购买 nike

我有一个如下所示的对象。

在第 6 行,我写了 console.log(this.title, elem)

现在根据我对this.-关键字的了解,this.title 不应该在这里引用当前对象,但是全局窗口对象。现在与我的知识相反,this.title 似乎正确引用了视频对象的属性。

const video = {
title: "a",
tags: ["a", "b", "c", "d"],
showTags() {
this.tags.forEach(elem => {
console.log(this.title + ": ", elem)
});
}
}
video.showTags();

这是浏览器显示的内容:

a:  a
a: b
a: c

我认为,由于 console.log(this.title, elem) 位于回调函数中,因此将引用全局窗口对象。 This post证实了我的观点,即 this.title 实际上应该引用全局对象。

谁能解释一下?

最佳答案

箭头函数在词法上绑定(bind)它们的上下文,因此 this 实际上指的是原始上下文。由于您在这里使用了 Arrow 函数,因此 forEach() 方法中 this 的值指向声明它的词法环境。它位于 showTags() 方法内部,因此它具有与 showTags() 相同的 this 值。

如果这里没有使用箭头函数,那么 this 的值将是 window,如下面的代码片段所示:

const video = {
title: "a",
tags: ["a", "b", "c", "d"],
showTags() {
this.tags.forEach(function(elem ) {
console.log(this.title, elem)
});
}
}
video.showTags();

关于javascript - 这。引用对象而不是窗口对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55926892/

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