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

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

    The issue with your solution is that it just makes you code harder to understand while still keeping all the downsides of global variables. The page you linked to covers the problems. The only problem your proposed solution really solves is namespace pollution but at the cost of not being able to see what global variables are declared as easily as the declaration is a function call).

    The solution is to write code without global variables. If a function needs a value pass it as a argument.

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

    Global state causes problems in several areas. One is code reuse. When you access some global state that means the component must be aware of it's environment(something outside of itself). You should avoid this as much as possible, because it makes the component unpredictable.

    Say I have an object that accesses your globalVariables function and I want to use it in another page. How do I know to define the globalVariables object or even how to define it? However if you can pass the information into a constructor or as an argument to a function then I can easily determine what is required by the object.

    Also when you access or modify the global scope then you risk affecting other objects. This is why libraries like jquery use only a single name on the global scope(the least possible). It lessens the possibility of conflict with other libraries. In other words the global scope is out of your control, so it is dangerous.

    0 讨论(0)
  • 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();

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

    Using global variables is generaly speaking a bad practice, regardless of the language of choice. They are not even (easily) allowed to use when at strict mode, which I highly recommend.

    Consider this piece of code I found:

    if (typeof session != 'undefined' && !data.cart.request_status)
      data.input_definitions.passengers =
        inflate_passenger(session, data.input_definitions.passengers);
    

    I needed to turn around and ask a felow programmer where did this session variable came from, as no code search showed up where was set.

    I turned out another package from the company sets the global variable. Code it's like a joke: if you need to explain it it's probably not that good.

    Workaround using ES6:

    If at Node, use import or require to bring the desired stuff into lexical scope, don't let people touch your global environment without you knowing it.

    import {Sesssion} from 'api-core';
    const Session = require('api-core').session;
    

    If you are at the frontend delivering code for the browser you can't use import unless you transpile your ES6 code using Babel.

    Example transpiling using Gulp.js:

    // $ npm install --save-dev gulp-babel babel-preset-es2015
    
    // gulpfile.js
    const gulp  = require('gulp');
    const babel = require('gulp-babel');
    
    gulp.task('transpile', () => {
      return gulp.src('src/app.js')
        .pipe(babel({presets: ['es2015']}))
        .pipe(gulp.dest('dist'));
    });
    
    // $ gulp transpile
    

    Legacy workaround:

    When using ES6 features is not an option the only workaround to using a bunch of global variables, is using only one, and have hope:

    // scripts/app.js
    var MyApp = {
      globals: {
        foo: "bar",
        fizz: "buzz"
      }
    };
    
    0 讨论(0)
  • 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

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

    The primary reason why global variables are discouraged in javascript is because, in javascript all code share a single global namespace, also javascript has implied global variables ie. variables which are not explicitly declared in local scope are automatically added to global namespace. Relying too much on global variables can result in collisions between various scripts on the same page (read Douglas Crockford's articles).

    One way to reduce global variables is to use the YUI module pattern. The basic idea is to wrap all your code in a function that returns an object which contains functions that needs to be accessed outside your module and assign the return value to a single global variable.

    var FOO = (function() {
        var my_var = 10; //shared variable available only inside your module
    
        function bar() { // this function not available outside your module
            alert(my_var); // this function can access my_var
        }
    
        return {
            a_func: function() {
                alert(my_var); // this function can access my_var
            },
            b_func: function() {
                alert(my_var); // this function can also access my_var
            }
        };
    
    })();
    

    now to use functions in your module elsewhere, use FOO.a_func(). This way to resolve global namespace conflicts you only need to change the name of FOO.

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