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

后端 未结 9 858
暖寄归人
暖寄归人 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: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"
      }
    };
    

提交回复
热议问题