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

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

提交回复
热议问题