简体   繁体   中英

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.

Typically, we do something like:

grid.js

var myGrid = .....

combos.js

var myCombo = .....

Then, in our application code, we:

application.js

function blah() {
    myGrid.someMethod()
}

someother.js

function foo() {
    myCombo.someMethod();
    myGrid.someMethod();
}

So, should we be using the var myGrid or is better to use 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.

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 = {};

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:

  1. You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)
  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)

PS: if you need to expose the internal components then add them to this inside the constructor function

One nice use of window.variable is that you can check it without having a javascript error. For example, if you have:

if (myVar) {
    //do work
}

and myVar is not defined anywhere on the page, you will get a javascript error. 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.

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.

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.

The general answer to the question would be to use var .

More specifically, always put your code in an Immediately Invoked Function Expression (IIFE) :

(function(){
  var foo,
      bar;
  ...code...
})();

This keeps variables like foo and bar from polluting the global namespace. Then, when you explicitly want a variable to be on the global object (typically window ) you can write:

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.

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

To expand on what Liviu said, use:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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