Sunday, April 8, 2012

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?



Source: Tips4all

3 comments:

  1. 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.

    ReplyDelete
  2. In addition to other answers, worth noting is that if you don't use var inside a function while declaring a variable, it leaks into global scope automatically making it a property of window object (or global scope).

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

    More specifically, always put your code in a closure:

    (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;


    Closures are JavaScript's form of encapsulation, 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.

    ReplyDelete