如何更改函数内部的全局变量的值 [英] How do I change the value of a global variable inside of a function

查看:205
本文介绍了如何更改函数内部的全局变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript并创建一个全局变量。我在函数之外定义它,我想从函数内部更改全局变量值并从另一个函数使用它,我该怎么做?

I am using JavaScript and I create a global variable. 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?

推荐答案

只需引用函数内部的变量;没有魔法,只要用它的名字。如果它是全局创建的,那么您将更新全局变量。

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.

您可以通过使用 var ,但是如果你不使用 var ,那么如果该变量已被全局声明,那么函数中使用的变量名将是全局的。

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 显式声明变量的最佳做法。因为如果你忘了它,你可以意外地开始搞乱全局变量。这是一个容易犯的错误。但在你的情况下,这转变并成为你问题的简单答案。

That's why it's considered best practice to always declare your variables explicitly with 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.

这篇关于如何更改函数内部的全局变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆