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

问题描述:

我见过使用window.global_name定义的全局变量。
我想知道为什么不使用global_name,即使这个脚本将在关闭时运行。

I've seen global variables defined with window.global_name. I wonder why not just using global_name even if this script will be run in closure.

UPD :好像IE没有'当你在一个闭包中声明它时,显式地将它添加到window对象中

UPD: seems like IE doesn't explicitly add it to the window object, when you declare it inside of a closure

作用域链中的最后一个对象任何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; })();