javascript 中的全局变量和 window.variable 之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6349232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:22:04  来源:igfitidea点击:

What's the difference between a global var and a window.variable in javascript?

javascriptattributesscope

提问by Derick Bailey

I'm reading the backbone.js documents and seeing a lot of code that assigns attributes to the window object:

我正在阅读backbone.js 文档并看到很多将属性分配给 window 对象的代码:

window.something = "whatever";

what's the difference between calling this code, and just assigning the variable and creating a global var, like this:

调用此代码与仅分配变量并创建全局变量之间有什么区别,如下所示:

something = "whatever";

i assume there is some kind of scope different, 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.

我假设存在某种范围不同和/或对象所有权差异(窗口是所有者与不是所有者)但我对两者之间的细节以及为什么我会使用窗口与不使用它感兴趣。

采纳答案by Raynos

No difference. They both have the same effect (In the browser, where windowis the global context1).

没有不同。它们都具有相同的效果(在浏览器中,window全局上下文1在哪里)。

  • window.foo = "bar"sets the property fooon window.
  • foo = "bar"indicates either a typoor intentionally global.
  • window.foo = "bar"设置该属性foowindow
  • foo = "bar"表示打字错误或故意全局。

Since I have to double check whether it's a typo or not, I personally find it more readableto set window.foodirectly.

由于我必须仔细检查它是否是一个错字,我个人觉得直接设置它更具可读性window.foo

Also, in ES5 strict mode, foo = "bar"is an illegal assignment because foois not declared and will throw a Error.

此外,在 ES5 严格模式下,foo = "bar"是非法赋值,因为foo未声明并且会抛出Error.

Edit:

编辑:

As noted in the comments, foo = "bar"will look all the way up the scope chain for the variable fooand re-assign it with "bar"if it's found. If it's not found, it will create a new global variable.

如评论中所述,foo = "bar"将一直向上查找变量的作用域链foo"bar"如果找到则重新分配它。如果没有找到,它将创建一个新的全局变量。

Also with window.foo = "bar"you're just assigning a property to an object, which can be deleted using delete window.foo.

此外,window.foo = "bar"您只需将一个属性分配给一个对象,该对象可以使用delete window.foo.

In ES5 strict mode it is invalidto deletea variable.

在ES5严格模式下是无效的,以delete一个变量。



1In other environments, such as node.js and Web Workers, there may be another name for the global object and windowmay not exist at all. Node.js uses globaland Web Workers use self.

1在其他环境中,例如node.js 和Web Workers,全局对象可能有另一个名称,window可能根本不存在。Node.js 使用global和 Web Workers 使用self.

回答by gion_13

They both kind of do the same thing.
But by accessing a windowproperty, you know for sure that you're accessing a global variable no matter what scope you're in.
For example :

他们都做同样的事情。
但是通过访问一个window属性,你肯定知道你正在访问一个全局变量,无论你在什么范围内。
例如:

globalVar = "smth";
function(){
    var globalVar = 2;
    alert(globalVar);// points to the current scope globalVar
    alert(window.globalVar);// points to the original globalVar
}

In other words, If you want to work with globals, it's somewhat safer to access them via their container : window.variable

换句话说,如果你想使用全局变量,通过它们的容器访问它们会更安全: window.variable

回答by ScottKoon

The key, as Raynos alluded to, is that it's set explicitly on the window object. In the browser, the global object is the same as the window object but in other environments (e.g. node.js, or perhaps running in a web view of some sort on a mobile device), it may not.

正如 Raynos 所提到的,关键是它是在 window 对象上显式设置的。在浏览器中,全局对象与窗口对象相同,但在其他环境中(例如 node.js,或者可能在移动设备上的某种 web 视图中运行),它可能不是。

回答by david

The difference is that window.foo = bar;cannot be intercepted by refactoring done later. Using foo = bar;means that if, at a later date, the code is moved into a closure where var foohas been defined, it will no longer set it on the global object.

不同的是window.foo = bar;不能被后面的重构拦截。使用foo = bar;意味着,如果在以后将代码移动到var foo已定义的闭包中,它将不再将其设置在全局对象上。

回答by SridharKritha

Adding one more point:

再补充一点:

If you refer an undeclared variabledirectly (without using - windowor typeof) then you will get a variable is not defined error.

如果你是指一个未声明的变量直接(不使用-窗口typeof运算),那么你会得到一个变量没有定义的错误

Examples:

例子:

// 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
}

回答by bee

Unresolved references (aka undeclared variables) are actually not variables, they get added as a property to the global object. [5c]

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

In strict mode ("use strict"), unresolved references throw a ReferenceError. This is to avoid adding properties to the global object that were meant to be declared variables. In this case if you do want to add a property to the global object you would use window.foo = "bar". [5a]

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