Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

javascript - 如何更改函数内部的全局变量的值(How do I change the value of a global variable inside of a function)

I am using JavaScript and I create a global variable.(我正在使用JavaScript,我创建了一个全局变量。)

I define it outside of a function and I want to change the global variable value from inside a function and use it from another function, how do I do this?(我在函数之外定义它,我想从函数内部更改全局变量值并从另一个函数使用它,我该怎么做?)   ask by NullPoiиteя translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(但在你的情况下,这种转变并成为你问题的简单答案。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...