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

后端 未结 9 674
暖寄归人
暖寄归人 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:39

    var ASHIVA_HandsOffNHS = (function() {
        
        // VARIABLES
    
        var my_var = 10;
    
    
        // PRIVATE FUNCTIONS
        
        function bar() {
            window.alert(my_var + 5);
        }
    
    
       // PUBLIC OBJECT
    
        myObject = {};
        
        myObject['a_func'] = function() {
                my_var += 10;
                window.alert(my_var);
            };
            
        myObject['b_func'] = function() {
                my_var = 0;
                window.alert(my_var);
            };
    
        return myObject;
    
    })();
    
    ASHIVA_HandsOffNHS.a_func();
    ASHIVA_HandsOffNHS.b_func();
    ASHIVA_HandsOffNHS.a_func();

提交回复
热议问题