JavaScript 中的这个

2023-12-23

我在 javascript 中使用“this”时遇到了一个令人困惑的问题。我有一个方法“get_data”,它返回对象的一些成员变量。有时它会将对象本身返回给我......我不知道为什么。有人能解释一下这里发生了什么吗?

function Feed_Item(data) {
  this.data = data;
  this.get_data = function() {
    return this.data;
  }

  this.foo = function() {
    return this.foo2();
  }
  this.foo2 = function() {
    //here type of this.data() == Feed_Item!!! It should be of type Data
  }
  this.bar = function() {
    //here type of this.data() == Data, as I'd expect
  }
}

JavaScript 中的“this”是什么取决于您如何调用该函数。如果“this”未绑定到对象,则 this 将是窗口对象。

如果你打电话

item = new Feed_Item()
item.foo() //foo will be called with correct 'this'

但是如果您执行 Feed_Item(some_data),您将向全局窗口对象添加几个函数。

有很多文章解释this, e.g. http://www.digital-web.com/articles/scope_in_javascript/ http://www.digital-web.com/articles/scope_in_javascript/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中的这个 的相关文章