Should I use window.variable or var?

前端 未结 7 1675
生来不讨喜
生来不讨喜 2020-12-02 12:25

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

7条回答
  •  清歌不尽
    2020-12-02 12:37

    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.

提交回复
热议问题