【问题标题】:What is the value of "this" inside a function passed to __defineGetter__传递给 __defineGetter__ 的函数中“this”的值是多少
【发布时间】:2012-12-07 08:49:55
【问题描述】:

我从 grunt npm 模块的源代码中看到以下代码行 -

String.prototype.__defineGetter__(method, function() { return this; });

只是试图预测上面匿名函数中“this”的值 -

  • 它指向“方法”
  • 全局“窗口”对象,如果在浏览器中运行,或者从 grunt 的角度来看类似的东西
  • 如果在“defineGetter”定义中使用了调用或应用,则其他内容取决于 defineGetter 的定义。

感谢您的帮助!!

【问题讨论】:

  • 因为console.log()是2011年?

标签: javascript scope this npm anonymous-function


【解决方案1】:

this 将是发生 get 操作的对象,我认为将始终是您调用 __defineGetter__ 的对象(因为我无法立即看到将该功能转移到其他地方,但我不保证您不能;不过,您必须故意这样做)。

值得注意的是,__defineGetter__ 是非标准且已过时的。目前定义getter的方法是使用Object.defineProperty或Object.defineProperties,像这样:

Object.defineProperty(String.prototype, "foo", {
  get: function() {
    // Here, `this` is the string
    return this.toUpperCase();
  }
});

console.log("hi there".foo);

...记录"HI THERE"。

Live Example | Source

【讨论】:

  • 闪电般的快!!很好的例子,非常详细,消除了所有疑虑。谢谢回答。 StackOverflow 摇滚!!
  • @ɟɐɹɐs ןoɯuɐ:哈哈!很高兴有帮助!最好的,
猜你喜欢
  • 2018-09-26
  • 2011-12-07
  • 2016-12-11
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多