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?


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:

  • 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
  • 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


    功能上潜在的重要区别是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 )
    

    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.

    链接地址: http://www.djcxy.com/p/96522.html

    上一篇: JavaScript变量范围问题:var,或不var

    下一篇: 我应该使用window.variable还是var?