【发布时间】:2010-04-14 13:10:55
【问题描述】:
前几天我遇到了一个有趣的问题,想知道是否有人可以解释为什么会发生这种情况。这是我正在做的事情(为了这个例子的目的,我稍微简化了这个例子):
- 我正在使用方括号表示法创建一个全局范围的变量并为其分配一个值。
-
稍后我声明了一个与我刚刚在上面创建的同名的 var。注意我没有赋值。由于这是对同一变量的重新声明,因此不应按照此处所述覆盖旧值:http://www.w3schools.com/js/js_variables.asp
//create global variable with square bracket notation window['y'] = 'old'; //redeclaration of the same variable var y; if (!y) y = 'new'; alert(y); //shows New instead of Old 问题是旧值实际上确实被覆盖了,并且在上面的例子中。警报显示“新”而不是“旧”。为什么?
我想另一种表达我的问题的方式是,上面的代码在语义方面与下面的代码有何不同:
//create global variable
var y = 'old';
//redeclaration of the same variable
var y;
if (!y) y = 'new';
alert(y); //shows Old
更新 1 :根据一些 cmets 和答案,我将重新表述该示例以更能反映我原来的问题。
创建 2 个包含以下内容的 javascript 文件: 脚本1
//create global variable with square bracket notation
window['y'] = 'old';
脚本2
//redeclaration of the same variable
var y;
if (!y) y = 'new';
alert(y); //shows New instead of Old in IE
在你的 html 文件中包含这两个文件
<html>
<head></head>
<body>
<script type="text/javascript" src="my.js"></script>
<script type="text/javascript" src="my2.js"></script>
</body>
</html>
在 Firefox 和 Chrome 中打开此页面会提示“旧”,这是预期的行为。但是在 IE 8 中,页面实际上会提示“新”
更新 2 问题移至此处:Redeclared javascript global variable overrides old value in IE
【问题讨论】:
-
你愚蠢的部分一定是所有这些代码都在一个函数中,给 var y 一个与 window.y 不同的范围
-
您的更新应该是一个新问题,特别是因为它是特定于浏览器的。
标签: javascript global-variables scope