Javascript 为什么全局变量被认为是不好的做法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10525582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:43:18  来源:igfitidea点击:

Why are global variables considered bad practice?

javascriptglobal-variablesglobal

提问by user1318416

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 imagine this being easily fixed by putting all of the variables into one big object. Now the question is: are there any other reasons not to use global variables other than convenience sake? Are there any performance or compatibility issues involved with them?

我一直看到警告不要在 JavaScript 中使用全局变量,但似乎人们这么说的唯一原因是因为它阻塞了全局命名空间。我可以想象通过将所有变量放入一个大对象中可以轻松解决这个问题。现在的问题是:除了方便之外,还有其他不使用全局变量的原因吗?它们是否存在任何性能或兼容性问题?

回答by Elliot Bonneville

They clutter up the global namespace and are slower to look up than local variables.

它们弄乱了全局命名空间,并且查找速度比局部变量慢。

First of all, having many global variables is always a bad thing because it's easy to forget you declared a variable somewhere and accidentally re-declare it somewhere else. If your first variable was local then you don't have a problem. If it was global, then it just got overwritten. This gets even worse when you get into implied globals (e.g. when you say someVar = someValuewithout declaring someVar with the varkeyword).

首先,拥有许多全局变量总是一件坏事,因为很容易忘记您在某处声明了一个变量,并意外地在其他地方重新声明了它。如果您的第一个变量是本地变量,那么您就没有问题。如果它是全局的,那么它就会被覆盖。当您进入隐含的全局变量时,someVar = someValue情况会变得更糟(例如,当您没有用var关键字声明 someVar 时)。

Secondly, global variables take longer for Javascript to "find" than local variables. The difference in speed isn't huge, but it doesexist.

其次,与局部变量相比,Javascript“查找”全局变量需要更长的时间。速度上的差异并不大,但确实存在。

For further reading and a more in-depth explanation of why globals are considered bad practice, you may want to check out this page.

要进一步阅读和更深入地解释为什么全局变量被认为是不好的做法,您可能需要查看此页面

回答by undeniablyrob

Global variables can significantly increase coupling, significantly reduces the scalability and testability of your code. Once you start using globals, you now have to know where and how the variable is modified (i.e. breaking encapsulation). Most of the literature and conventions out there will argue that performance is the least of your concerns when using globals.

全局变量会显着增加耦合,显着降低代码的可扩展性和可测试性。一旦您开始使用全局变量,您现在必须知道在哪里以及如何修改变量(即破坏封装)。大多数文献和惯例都会争辩说,在使用全局变量时,性能是您最不关心的问题。

This is a fantastic article outlining whyglobal variables cause headaches.

这是一篇很棒的文章,概述了为什么全局变量会让人头疼。

回答by Tyler McGinnis

In a nutshell, Global variables cause (and more) the following issues.

简而言之,全局变量会导致(以及更多)以下问题。

1) Variable naming collisions - If you're working on a team and both yourself and your co-worker use the same variable name on the global scope, the variable defined last will overwrite the initial variable. This obvious can have devastating consequences.

1) 变量命名冲突——如果你在一个团队中工作并且你自己和你的同事在全局范围内使用相同的变量名,最后定义的变量将覆盖初始变量。这种明显的后果可能会造成毁灭性的后果。

2) Security - Specifically on the web, every user has access to the Window (or global) object. By putting variables on the global scope, you give any user the ability to see or change your variables.

2) 安全性 - 特别是在网络上,每个用户都可以访问 Window(或全局)对象。通过将变量放在全局范围内,您可以让任何用户查看或更改您的变量。

3) Slower - This is arguably negligible, but it still exists. The way JavaScript variable lookups work is the JavaScript engine will do a lookup on the current scope the variable is being looked up in. If it can't find it, it will do a look up on the next parent scope. If it doesn't find it there, it will continue looking upward until it reaches the global object looking for that variable. If all of your variables are located on the global scope, the JavaScript engine will always have to go through every scope in order to finally reach the global scope to find the variable.

3) 较慢 - 这可以说是可以忽略不计,但它仍然存在。JavaScript 变量查找的工作方式是 JavaScript 引擎将在当前查找变量的作用域上进行查找。如果找不到,它将查找下一个父作用域。如果在那里找不到它,它将继续向上查找,直到它到达寻找该变量的全局对象。如果您的所有变量都位于全局范围内,则 JavaScript 引擎将始终必须遍历每个范围才能最终到达全局范围以找到变量。

回答by Roberto Linares

If your script is very long and you use these variables from lots of functions it will increase your debugging time since the value of the global variable could have been changed from anywhere so if you are tracking where this changed to a non-expected value you'll have to check them all.

如果您的脚本很长并且您从许多函数中使用这些变量,这将增加您的调试时间,因为全局变量的值可能已从任何地方更改,因此如果您正在跟踪更改为非预期值的位置必须全部检查。

This scenario is even more painful if different programmers modify this variable from other scripts included in your page.

如果不同的程序员从页面中包含的其他脚本修改此变量,则这种情况会更加痛苦。

回答by yoav barnea

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)

只要您将全局变量包装在 uniqe 命名空间/对象中(以避免与不属于您的脚本发生冲突),在代码中使用全局变量应该不会有任何问题

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...)

在 javascript 中使用全局变量有一个好处,它源于 javascript 不是一种强类型语言这一事实​​。因为,如果您将一些复杂对象作为参数传递给函数,您可能会丢失这些对象的所有智能(在函数作用域内)。而使用全局对象代替,将保留该智能。当你有智能时,它实际上可以改善调试时间(与其他人所说的相反......)

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)

(当然,应该始终在本地变量和全局变量之间取得适当的平衡)

回答by Danilo Valente

Basically, because they can be accessed from any script on the page and because you can repeat it's name in the same scope. That's why a lot of Javascript engines use this code:

基本上,因为它们可以从页面上的任何脚本访问,并且因为您可以在同一范围内重复它的名称。这就是为什么许多 Javascript 引擎使用此代码的原因:

(function(){
    var foo = 'foo',//Local
    bar = 'bar';//Local
    window.globalVar = foo + bar;//Global
})();
alert(foo);//Error
alert(bar);//Error
alert(globalVar );//'foobar'

回答by Apoorv Nag

The global variable which you have created might overwrite the existing window object properties. Because the global variables are accessing in global context i.e. window object.

您创建的全局变量可能会覆盖现有的窗口对象属性。因为全局变量是在全局上下文中访问的,即窗口对象。