Just reference the variable inside the function;(只需引用函数内部的变量;)
no magic, just use it's name.(没有魔法,只要用它的名字。) If it's been created globally, then you'll be updating the global variable.(如果它是全局创建的,那么您将更新全局变量。)
You can override this behaviour by declaring it locally using var
, but if you don't use var
, then a variable name used in a function will be global if that variable has been declared globally.(您可以通过使用var
在本地声明它来覆盖此行为,但如果不使用var
,则如果已全局声明该变量,则函数中使用的变量名称将为全局。)
That's why it's considered best practice to always declare your variables explicitly with var
.(这就是为什么始终使用var
显式声明变量的最佳实践。)
Because if you forget it, you can start messing with globals by accident.(因为如果你忘了它,你可以意外地开始搞乱全局变量。) It's an easy mistake to make.(这是一个容易犯的错误。) But in your case, this turn around and becomes an easy answer to your question.(但在你的情况下,这种转变并成为你问题的简单答案。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…