I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

后端 未结 9 660
暖寄归人
暖寄归人 2020-11-22 03:26

I\'ve read all over the place that global variables are bad and alternatives should be used. In Javascript specifically, what solution should I choose.

I\'m thinking

相关标签:
9条回答
  • 2020-11-22 03:53

    Semantics my boy. Semantics.

    Start with one global: myApp = {}; Everything should be in that. The only exception would be your AJAX library (there are some extreme exceptions like working with JSONP callbacks).

    There should be very few properties in myApp. You'll want to hold your application properties in containers such as config or settings.

    myApp = {
        config:{
            prop:1
        },
        settings:{
            prop:2
        },
        widgets:{
            List: function(props){},
            Item: function(props){}
        }
    }
    

    Then you may have more properties in lower modules, components, singletons and Class constructors (widgets).

    This setup gives you the added benefit of being able to access any property from any other location since you can get it with the myApp global. However, you should use "this" whenever possible because the lookup is faster. And just set the property directly, don't bother with the pseudo getter/setter stuff. If you really need a getter/setter, code it for that specific use.

    The reason your example doesn't work is it's too generic and you seem to be looking for an excuse to work in the global space.

    And don't get clever with private variables. They're bad too: http://clubajax.org/javascript-private-variables-are-evil/

    0 讨论(0)
  • 2020-11-22 03:57

    You really don't want to do this.
    As to why, see e.g. the top post here: What is the most EVIL code you have ever seen in a production enterprise environment?

    As a side note, one can always execute "global" code without littering the place with globals:

    (function () {
        var notaglobal = 1;
        alert(notaglobal);
    })();
    //notaglobal is not defined in this scope        
    
    0 讨论(0)
  • 2020-11-22 03:57

    Global variables are bad... if left unmanaged!

    The potential risks of global variables is as high as the pleasure and productivity gains of having frequently used objects ready to use.

    I don't believe one should seek a single alternative. Instead I advocate for one object in charge of managing those globals and as the code base/component matures, refactor them out

    One thing not mentioned in the current answers which I think is critical is an understanding of DI and IoC containers. These address many of the problems people try to solve with global variables, but covering related concerns that plain globals can't, like object life cycles.

    0 讨论(0)
提交回复
热议问题