且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript中的“窗口”始终位于范围链的顶部吗?

更新时间:2021-08-23 09:24:03

作用域链中的最后一个对象任何ECMAScript环境始终是全局对象。在浏览器中,窗口是全局对象的所有意图和目的。如果要访问全局对象的属性 x 或全局变量 x (几乎但不完全同样的事情),您应该使用 window.x 明确限定它,以避免 x 被解析为范围链上另一个对象的属性,或 globalObj.x ,如果您关心非浏览器环境的可移植性。您可以从ECMAScript 3或非严格ECMAScript 5中的任何位置获取对全局对象的引用,如下所示:

The last object on the scope chain in any ECMAScript environment is always the global object. In browsers, window is to all intents and purposes the global object. If you want to access a property of the global object x or a global variable x (which are almost but not quite the same thing), you should explicitly qualify it with window.x to avoid the possibility of x being resolved as a property of another object on the scope chain, or globalObj.x if you care about portability to non-browser environments. You can get a reference to the global object from anywhere in ECMAScript 3 or non-strict ECMAScript 5 as follows:

var globalObj = (function() { return this; })();