繁体   English   中英

JavaScript 中的全局变量和“window.variable”有什么区别?

[英]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 上设置它。

再补充一点:

如果您直接引用未声明的变量(不使用-windowtypeof ),那么您将得到一个 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
}

未解析的引用(又称未声明的变量)实际上不是变量,它们作为属性添加到全局 object。 [5c]

在严格模式(“使用严格”)中,未解析的引用会引发 ReferenceError。 这是为了避免向全局 object 添加要声明为变量的属性。 在这种情况下,如果您确实想向全局 object 添加属性,您将使用 window.foo = "bar"。 [5a]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM