传递给__defineGetter__的函数中"this"的值是多少?

Anm*_*raf 3 javascript scope this anonymous-function npm

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

String.prototype.__defineGetter__(method, function() { return this; });
Run Code Online (Sandbox Code Playgroud)

只是想在上面的匿名函数中预测"this"的价值 -

  • 它指回'方法'
  • 全局"窗口"对象,如果在浏览器中运行或类似于grunt的视角
  • 别的东西取决于定义defineGetter如果电话或应用是在"defineGetter"定义内使用.

谢谢您的帮助 !!

T.J*_*der 7

this将是get操作发生的对象,我认为它将永远是你调用的对象__defineGetter__(因为我无法立即看到将该函数转移到其他地方的方法,但我不保证你不能;但你必须故意这样做.

值得注意的是,这__defineGetter__是非标准和过时的.目前定义getter的方法是使用Object.definePropertyor Object.defineProperties,如下所示:

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

console.log("hi there".foo);
Run Code Online (Sandbox Code Playgroud)

...哪些日志"HI THERE".

实例 | 资源

  • 闪电快!! 很好的例子,非常详细,清除所有的疑虑.谢谢回答.StackOverflow Rocks !! (2认同)