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)
我想更好地理解这一点.
在 ES 3 和 ES 5 中,有一个this关键字与每个执行上下文 (ES 3) 或词法环境 (ES 5) 相关联。该值是根据输入全局或函数代码的规则设置的,如 ECMA-262 \xc2\xa710.4中所述。
\n\n在你的代码中你有:
\n\n this.global = (function () {return this;})(); \nRun 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| 归档时间: |
|
| 查看次数: |
1175 次 |
| 最近记录: |