Javascript 我应该使用 window.variable 还是 var?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6904166/
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
Should I use window.variable or var?
提问by cbmeeks
We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.
我们有很多设置 JS 代码,用于定义将在许多其他 JS 文件中使用的面板、按钮等。
Typically, we do something like:
通常,我们会执行以下操作:
grid.js
网格.js
var myGrid = .....
combos.js
组合.js
var myCombo = .....
Then, in our application code, we:
然后,在我们的应用程序代码中,我们:
application.js
应用程序.js
function blah() {
myGrid.someMethod()
}
someother.js
其他人.js
function foo() {
myCombo.someMethod();
myGrid.someMethod();
}
So, should we be using the var myGrid
or is better to use window.myGrid
那么,我们应该使用var myGrid
还是更好地使用window.myGrid
What's the difference?
有什么不同?
采纳答案by Liviu T.
I would suggest creating a namespace variable var App = {};
我建议创建一个命名空间变量 var App = {};
App.myGrid = ...
That way you can limit the pollution of the global namespace.
这样你就可以限制全局命名空间的污染。
EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:
编辑:关于变量数量问题 - 想到了 2 种可能的解决方案:
- You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)
- You encapsulate your methods in objects that get instantiated with the components you have
- 您可以通过类型(网格、按钮等)或关系(ClientInfoSection、AddressSection 等)进一步命名它们
- 您将方法封装在使用您拥有的组件实例化的对象中
ex: you have
例如:你有
function foo() {
myCombo.someMethod();
myGrid.someMethod();
}
becomes:
变成:
var Foo = function(combo, grid) {
var myCombo = combo;//will be a private property
this.myGrid = grid;//will be a public property
this.foo = function() {//public method
myCombo.someMethod();
myGrid.someMethod();
}
}
App.myFoo = new Foo(someCombo, someGrid);
App.myFoo.foo();
this way you limit the amount of little objects and only expose what you need (namely the foo function)
这样你就限制了小对象的数量,只暴露你需要的东西(即 foo 函数)
PS: if you need to expose the internal components then add them to this inside the constructor function
PS:如果你需要暴露内部组件,那么在构造函数中将它们添加到 this 中
回答by user113716
A potentially important difference in functionality is that window.myGrid
can be delete
d, and var myGrid
can not.
功能上一个潜在的重要差异是window.myGrid
可以delete
和var myGrid
不能。
var test1 = 'value';
window.test2 = 'value';
console.log( delete window.test1 ); // false ( was not deleted )
console.log( delete window.test2 ); // true ( was deleted )
console.log( test1 ); // 'value' ( still accessible )
console.log( test2 ); // ReferenceError ( no longer exists )
回答by aepheus
One nice use of window.variable
is that you can check it without having a javascript error. For example, if you have:
一个很好的用途window.variable
是您可以在没有javascript错误的情况下检查它。例如,如果您有:
if (myVar) {
//do work
}
and myVar
is not defined anywhere on the page, you will get a javascript error. However:
并且myVar
未在页面上的任何地方定义,您将收到 javascript 错误。然而:
if (window.myVar) {
//do work
}
gives no error, and works as one would expect.
没有错误,并且按预期工作。
var myVar = 'test'
and window.myVar = 'test'
are roughly equivalent.
var myVar = 'test'
并且window.myVar = 'test'
大致相等。
Aside from that, as other said, you should descend from one global object to avoid polluting the global namespace.
除此之外,正如其他人所说,您应该从一个全局对象下降以避免污染全局命名空间。
回答by Jeremy Roman
In global scope the two are in fact equivalent functionality-wise. In function scope, var
is certainly preferable when the behaviour of closures is desired.
在全局范围内,两者实际上在功能方面是等效的。在函数范围内,var
当需要闭包的行为时当然更可取。
I would just use var
all of the time: firstly, it's consistent with the usually preferred behaviour in closures (so it's easier to move your code into a closure if you decide to do so later), and secondly, it just feels more semantic to me to say that I'm creating a variable than attaching a property of the window. But it's mostly style at this point.
我会一直使用var
:首先,它与闭包中通常首选的行为一致(因此,如果您稍后决定将代码移动到闭包中会更容易),其次,它对我来说感觉更语义化说我正在创建一个变量而不是附加窗口的属性。但在这一点上主要是风格。
回答by zzzzBov
The general answer to the question would be to use var
.
这个问题的一般答案是使用var
.
More specifically, always put your code in an Immediately Invoked Function Expression (IIFE):
更具体地说,始终将您的代码放在立即调用函数表达式 (IIFE) 中:
(function(){
var foo,
bar;
...code...
})();
This keeps variables like foo
and bar
from polluting the global namespace. Then, when you explicitly wanta variable to be on the global object (typically window
) you can write:
这可以防止变量像foo
和bar
污染全局命名空间。然后,当您明确希望变量位于全局对象上时(通常为window
),您可以编写:
window.foo = foo;
JavaScript has functional scope, and it's really good to take full advantage of it. You wouldn't want your app to break just because some other programmer did something silly like overwrote your timer handle.
JavaScript 具有功能范围,充分利用它真的很好。你不希望你的应用程序因为其他程序员做了一些愚蠢的事情而崩溃,比如覆盖了你的计时器句柄。
回答by Mrchief
In addition to other answers, worth noting is that if you don't use var
inside a function while declaring a variable, it leaksinto global scope automatically making it a property of window
object (or global scope).
除了其他答案之外,值得注意的是,如果您var
在声明变量时不在函数内部使用,它会自动泄漏到全局范围内,使其成为window
对象(或全局范围)的属性。
回答by Justin Long
To expand on what Liviu said, use:
要扩展 Liviu 所说的内容,请使用:
App = (function() {
var exports = {};
/* code goes here, attach to exports to create Public API */
return exports;
})();
By doing that you can hide some of your implementation specific code, which you may not want exposed by using var
's inside. However, you can access anything attached to the exports
object.
通过这样做,您可以隐藏一些特定于实现的代码,您可能不希望通过var
在内部使用's 来公开这些代码。但是,您可以访问附加到exports
对象的任何内容。