全局变量 JavaScript(改变值)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2350085/
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
Global Variable JavaScript (Changing Value)
提问by muntasir
Is it possible to change the value of a global variable in JavaScript?
是否可以在 JavaScript 中更改全局变量的值?
If so, is it possible to do it in a function called by an event listener such as "onreadyStateChange"?
如果是这样,是否可以在诸如“onreadyStateChange”之类的事件侦听器调用的函数中执行此操作?
It's working for normal functions. but doesn't change when I call a function like this:
它适用于正常功能。但是当我调用这样的函数时不会改变:
<script.......>
var dom1 = 3;
function work()
{
...
http.onreadyStateChange=handleHttpResponse;
...
}
function handleHttpResponse()
{
var xd;
if (http.readyState == 4)
{
if (http.status == 200)
{
if (http.responseText == "granted")
{
dom1 = 1;
}
else
{
dom1 = 2;
}
}
else
{
alert("Error");
}
}
}
</script>
回答by outis
You can change the value of any variable in JS, local or global. In a function, make sure you don't declare a local variable with the same name and you can access the global. Even if you do declare a local, you can access the global as a property of window. You can change most properties as well; there are very few immutable data types in JS or the DOM.
您可以更改 JS 中任何变量的值,本地或全局。在函数中,请确保您没有声明具有相同名称的局部变量,并且您可以访问全局变量。即使您确实声明了本地,您也可以将全局作为window. 您也可以更改大多数属性;JS 或 DOM 中几乎没有不可变的数据类型。
If a variable isn't being set as you expect, you can use Firefox and firebugto debugthe code and observe what's happening.
回答by wong ka chun
Please use window['dom1'] = xxx; instead of var dom1 = xxx;
请使用 window['dom1'] = xxx; 而不是 var dom1 = xxx;
回答by wong ka chun
Please try:
请尝试:
<script type="text\javascript">
var dom1 = 3;
function work()
{
...
http.onreadyStateChange=handleHttpResponse;
...
}
function handleHttpResponse()
{
var xd;
if (http.readyState == 4)
{
if (http.status == 200)
{
if (http.responseText == "granted")
{
*window['dom1']* = 1;
}
else
{
*window['dom1']* = 2;
}
}
else
{
alert("Error");
}
}
}
</script>
You would find the global value "dom1" is finally changed!
你会发现全局值“dom1”终于改变了!

