将JavaScript局部变量转换为全局变量 [英] Turn a JavaScript local variable into a global variable
问题描述
我有一个JavaScript函数来生成变量.该功能由onclick按钮事件激活.
I have a JavaScript function to generate a variable. That function is activated by an onclick button event.
生成该变量后,我需要将其用作全局变量,以便其他JavaScript进程可以使用该变量.
After that variable is generated, I need to use it as a global variable so that other JavaScript processes can use that variable.
我该怎么做?
推荐答案
您应该能够将变量的值添加到全局 window
对象的属性中:
You should be able to add the variable's value to a property of the global window
object:
window.yourVarName = yourVarName;
然后,其他功能只需直接引用 yourVarname
即可访问 yourVarName
.无需使用 window.yourVarName
.
Then the other functions will be able to access yourVarName
simply by referencing yourVarname
directly. There will be no need to use window.yourVarName
.
However keep in mind that in general, global variables are evil.
这篇关于将JavaScript局部变量转换为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!