Why are global variables considered bad practice?

后端 未结 7 1546
野趣味
野趣味 2020-11-22 03:19

I keep seeing warnings not to use global variables in JavaScript, but it seems that the only reason people say that is because the clogs up the global namespace. I can imagi

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:42

    There shouldn't be any problem using global variables in your code as long as you are wrapping them inside a uniqe namespase/object (to avoid collision with scripts that are not yours)

    There is one adventage of using global variable in javascript, and it derives from the fact that javascript is not a strong type language. there for, if you pass somes complex objects as arguments to a function, you will probebly lose all the intellisence for those objects (inside the function scope.) while using global objects insteads, will preserve that intellisence. and when you have intelisence, it actually can improve the debugging time (as opposed to what others said...)

    I personally find that very usful and it certainly have place in my code.

    (of course, one should alwayse make the right balance between locals and globals variables)

提交回复
热议问题