我有一个如下所示的对象。
在第 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()
方法内部,因此它的 this
值与 showTags()
的值相同。
如果这里没有使用箭头函数,那么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/