Should I use window.variable or var?

前端 未结 7 1685
生来不讨喜
生来不讨喜 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:42

    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.

提交回复
热议问题