简体   繁体   English

我应该使用window.variable还是var?

[英]Should I use window.variable or var?

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 grid.js

var myGrid = .....

combos.js combos.js

var myCombo = .....

Then, in our application code, we: 然后,在我们的应用程序代码中,我们:

application.js 的application.js

function blah() {
    myGrid.someMethod()
}

someother.js someother.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? 有什么不同?

A potentially important difference in functionality is that window.myGrid can be delete d, and var myGrid can not. 功能上一个潜在的重要区别是window.myGrid可以delete d, var myGrid不能delete

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 )

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个可能的解决方案:

  1. You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc) 您可以通过类型(网格,按钮等)或关系(ClientInfoSection,AddressSection等)进一步命名它们。
  2. You encapsulate your methods in objects that get instantiated with the components you have 您将方法封装在使用您拥有的组件实例化的对象中

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:如果需要公开内部组件,则将它们添加到构造函数内部

One nice use of window.variable is that you can check it without having a javascript error. window.variable一个很好的用途是你可以检查它而不会出现javascript错误。 For example, if you have: 例如,如果您有:

if (myVar) {
    //do work
}

and myVar is not defined anywhere on the page, you will get a javascript error. 并且myVar未在页面的任何位置定义,您将收到javascript错误。 However: 然而:

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. 除此之外,正如其他人所说,你应该从一个全局对象下降,以避免污染全局命名空间。

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. 我会一直使用var :首先,它与闭包中通常首选的行为一致(因此,如果您稍后决定将代码移动到闭包中会更容易),其次,它只会感觉更加语义化我要说我正在创建一个变量而不是附加窗口的属性。 But it's mostly style at this point. 但在这一点上它主要是风格。

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. 这使得像foobar这样的变量不会污染全局命名空间。 Then, when you explicitly want a variable to be on the global object (typically window ) you can write: 然后,当您明确希望变量位于全局对象(通常是window )上时,您可以编写:

window.foo = foo;

JavaScript has functional scope, and it's really good to take full advantage of it. JavaScript具有功能范围,充分利用它是非常好的。 You wouldn't want your app to break just because some other programmer did something silly like overwrote your timer handle. 你不希望你的应用程序破解只是因为其他程序员做了一些愚蠢的事情,就像覆盖你的计时器句柄一样。

除了其他答案之外,值得注意的是,如果在声明变量时不在函数内部使用var ,它会自动泄漏到全局作用域,使其成为window对象(或全局作用域)的属性。

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. 通过这样做,您可以隐藏一些特定于实现的代码,您可能不希望通过使用var内部来暴露这些代码。 However, you can access anything attached to the exports object. 但是,您可以访问附加到exports对象的任何内容。

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

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