Javascript 将javascript局部变量转换为全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2788159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
turn javascript local variable into global variable
提问by Eric Sim
I have a javascript function to generate a var. That function is activated by an onclick button event.
我有一个 javascript 函数来生成一个 var。该功能由 onclick 按钮事件激活。
After that var is generated, I need to use it as a global var so that other js processes can use that var.
生成该 var 后,我需要将其用作全局 var,以便其他 js 进程可以使用该 var。
How do I do it?
我该怎么做?
采纳答案by Daniel Vassallo
You should be able to add the variable's value to a property of the global windowobject:
您应该能够将变量的值添加到全局window对象的属性中:
window.yourVarName = yourVarName;
Then the other functions will be able to access yourVarNamesimply by referencing yourVarnamedirectly. There will be no need to use window.yourVarName.
然后其他函数将能够yourVarName通过yourVarname直接引用来访问。将不需要使用window.yourVarName.
However keep in mind that in general, global variables are evil.
但是请记住,一般来说,全局变量是邪恶的。
回答by roryf
Declare the variable outside the scope of the function:
声明函数范围之外的变量:
var foo = null;
function myClickEvent() {
foo = someStuffThatGetsValue;
}
Better yet, use a single global variable as the namespace for your application, and store the value inside that:
更好的是,使用单个全局变量作为应用程序的命名空间,并将值存储在其中:
var MyApp = {
foo: null
};
function myClickEvent() {
MyApp.foo = someStuffThatGetsValue;
}
The function itself could even be included in there
函数本身甚至可以包含在那里

