javascript中的“窗口”始终位于范围链的顶部吗? [英] Is 'window' always on top of the scope chain in javascript?

查看:87
本文介绍了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; })();

这篇关于javascript中的“窗口”始终位于范围链的顶部吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆