为什么闭包比保留变量的全局变量更好? [英] Why are closures better than global variables for preserving variables?
问题描述
我理解JavaScript中的闭包是如何工作的,但我的问题是为什么你会遇到制作闭包以保存变量的所有麻烦?难道你不能让变量全局化吗?或者这会使全局范围变得混乱并使您的代码容易出错。
I understand how closures work within JavaScript, but my question is why would you go through all the trouble of making a closure to preserve a variable? Couldn't you just make the variable global? Or would that clutter up the global scope and make your code be prone to errors.
推荐答案
这是一个范围问题。全局变量就是:全局变量,每个人。使用闭包,可以更好地控制变量的范围(可见性),这意味着可以更好地控制可能的意外副作用。
It's a scoping issue. Global variables are just that: Global, to everyone. With closures, the scope (visibility) of the variables can be better controlled, which means the possible unintended side effects can be better controlled.
http://en.wikipedia.org/wiki/Global_variable
[Globals]通常被认为是不好的做法正是因为它们的非本地性:全局
变量可以从任何地方修改(除非它们位于受保护的内存中),
和该计划的任何部分都可能依赖于它。因此,全局变量具有创建相互依赖性的
无限潜力,并且添加相互依赖性
会增加复杂性。请参阅远距离行动
这篇关于为什么闭包比保留变量的全局变量更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!