How do I change the value of a global variable inside of a function

前端 未结 5 758
野趣味
野趣味 2020-11-27 10:36

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 10:45

    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.

    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.

提交回复
热议问题