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

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

    Other answer most explain with anonymous function as this article mention,

    Anonymous functions are difficult to debug, maintain, test, or reuse.

    Here are example with normal function. It's easier to read and understand.

    /* global variable example */
    
        var a= 3, b= 6;
        
        function fwithglobal(){
        console.log(a, b); // 3 6 expected
        }
        
        fwithglobal(); // first call
        
        function swithglobal(){
        var a=9;
        console.log(a, b); // not 3 6 but 9 6
        }
        
        swithglobal(); // second call
        
    
    /* global variable alternative(function parameter) */
    
        function altern(){
        var a= 3, b= 6; // var keyword needed
          f_func(a,b);
          s_func(a,b);
        }
        
        function f_func(n, m){
        console.log(n, m); // 3 6 expected
        }
        
        function s_func(n, m){
        var a=9;
        console.log(n, m); // 3 6 expected
        }
        
        altern(); // only once

提交回复
热议问题