[英]What's the difference between a global variable and a 'window.variable' in JavaScript?
我正在阅读Backbone.js文档,并且看到很多将属性分配给window object 的代码:
window.something = "whatever";
调用此代码与仅分配变量并创建全局变量有什么区别,如下所示:
something = "whatever";
I assume there is some kind of scope difference, and/or object ownership difference ( window being the owner vs. not), but I am interested in the detail between the two and why I would use window vs. not use it.
没有不同。 它们都具有相同的效果(在浏览器中, window
是全局上下文1 )。
window.foo = "bar"
在window
上设置属性foo
。foo = "bar"
表示拼写错误或故意全局。 由于我必须仔细检查它是否是拼写错误,我个人认为直接设置window.foo
更具可读性。
此外,在 ES5 严格模式下, foo = "bar"
是非法赋值,因为foo
没有声明并且会抛出Error
。
编辑:
如评论中所述, foo = "bar"
将在 scope 链中一直查找变量foo
并在找到时将其重新分配为"bar"
。 如果没有找到,它将创建一个新的全局变量。
同样使用window.foo = "bar"
您只是将属性分配给 object,可以使用delete window.foo
。
在 ES5 严格模式下, delete
变量是无效的。
1在其他环境中,如 node.js 和 Web Worker 中,全局 object 和window
可能不存在其他名称。 Node.js 使用global
和 Web 工人使用self
。
他们都做同样的事情。
但是通过访问window
属性,您可以确定您正在访问一个全局变量,无论您在哪个 scope 中。
例如:
globalVar = "smth";
function(){
var globalVar = 2;
alert(globalVar);// points to the current scope globalVar
alert(window.globalVar);// points to the original globalVar
}
换句话说,如果你想使用全局变量,通过它们的容器访问它们会更安全一些: window.variable
正如 Raynos 所暗示的,关键是它在 window object 上明确设置。 In the browser, the global object is the same as the window object but in other environments (eg node.js, or perhaps running in a web view of some sort on a mobile device), it may not.
不同的是window.foo = bar;
无法通过稍后进行的重构来拦截。 使用foo = bar;
意味着如果以后代码被移动到定义了var foo
的闭包中,它将不再在全局 object 上设置它。
再补充一点:
如果您直接引用未声明的变量(不使用-window或typeof ),那么您将得到一个 variable is not defined错误。
例子:
// var unDecVariable
if (unDecVariable != null) // Error: unDecVariable is not defined
{
// do something
}
if (window.unDecVariable != null) // No Error
{
// do something
}
if (typeof unDecVariable != 'undefined' && unDecVariable != null) // Alternative way
{
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.