【问题标题】:this. references Object instead of Window-Object这。引用 Object 而不是 Window-Object
【发布时间】:2019-09-19 11:12:37
【问题描述】:

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

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

现在根据我对 this.-Keyword 的了解,this.title 不应该在这里引用当前的 Object,而是全局的 Window-Object。现在与我的知识相反,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) 在callBack-Function 中,所以会引用全局窗口对象。 This post 证实了我的观点,即 this.title 实际上应该引用全局对象。

谁能解释一下?

【问题讨论】:

  • showTags 是该对象的成员。

标签: javascript reference this window-object


【解决方案1】:

箭头函数在词法上绑定它们的上下文,所以 this 实际上是指原始上下文。由于您在此处使用Arrow 函数,因此forEach() 方法中this 的值指向声明它的词法环境。那是在showTags()方法里面,所以它的this值和showTags()的值是一样的。

如果这里没有使用箭头函数,那么this的值就是window,如下面的sn-p:

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

【讨论】:

  • 我刚刚尝试过,确实...arrow-函数让一切变得不同。我一直认为箭头符号只是语法改进的问题。谢谢!
  • @Josh 您可以将选中标记接受的答案标记为已接受,以帮助其他人找到更好的答案。
  • 我没有意识到作为新秀海报我被允许这样做。现在刚刚完成。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2021-12-31
  • 2018-05-24
  • 1970-01-01
  • 2011-01-12
  • 2014-12-11
  • 2019-08-07
相关资源
最近更新 更多