Is setting properties on the Window object considered bad practice?

后端 未结 3 524
暗喜
暗喜 2020-12-17 10:51

I\'m writing a quite complex JavaScript application that has an MVC architecture that I\'m implementing using Prototype\'s Class support and the Module pattern. The applicat

3条回答
  •  佛祖请我去吃肉
    2020-12-17 11:17

    Setting properties on the window object is equivalent to creating global variables. That is, sometimes doing it is inevitable, but you should try to keep it to a bare minimum, as it ends up polluting the global namespace.

    In your case, creating a single property is not so bad. If you want to be extra careful about it, you can explicitly create a namespace for any stuff you need global access to:

    // In init:
    var mynamespace = {};
    
    . . .
    
    // Once the controller is available:
    var namespace = window.mynamespace;
    namespace.controller = controller;
    namespace.foo = bar; // Set other stuff here as well.
    

提交回复
热议问题