为什么这会返回对全局窗口对象的引用,即使'this'在另一个函数内

Joe*_*abo 5 javascript

if (typeof obj == 'undefined') {
  obj = {};
}

obj.thing = new function () {
  if (typeof this.global == 'undefined') {
    this.global = (function () {return this;})();
  }
}
Run Code Online (Sandbox Code Playgroud)

this.global被分配给函数内部.那么,为什么这会返回对窗口对象的引用?

console.log(this) > DOMWindow
console.log(obj.thing.global) > DOMWindow
console.log(window) > DOMWindow
Run Code Online (Sandbox Code Playgroud)

我想更好地理解这一点.

Rob*_*obG 1

在 ES 3 和 ES 5 中,有一个this关键字与每个执行上下文 (ES 3) 或词法环境 (ES 5) 相关联。该值是根据输入全局或函数代码的规则设置的,如 ECMA-262 \xc2\xa710.4中所述。

\n\n

在你的代码中你有:

\n\n
  this.global = (function () {return this;})();  \n
Run Code Online (Sandbox Code Playgroud)\n\n

其中调用匿名函数的结果被分配给this.global在该匿名函数中, this的值根据\xc2\xa710.4.3中的算法设置。

\n\n

由于调用该函数时没有设置this的值,并且代码未处于严格模式,因此根据算法的第 2 步,将this的值设置为全局对象(在浏览器中通常是 window 对象) 。

\n\n

如果代码处于严格模式,则匿名函数中的this值将为undefined,该值将分配给this.global

\n