我有一天遇到了一个有趣的问题,并想知道是否有人可以阐明为什么会发生这种情况。这是我在做什么(为了这个例子的目的,我已经淡化了这个例子):Javascript redeclared全局变量覆盖旧值
- 我使用方括号表示法创建一个全局作用域变量并为其赋值。
后来我声明了一个与我刚才创建的名称相同的变量。注意我没有分配一个值。由于这是同一个变量的重复声明如下描述的旧值不应该被重写: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:基于一些评论和回答我正在改写这个例子,以更加反映我原来的问题。
与以下内容创建2个JavaScript文件: SCRIPT1
//create global variable with square bracket notation
window['y'] = 'old';
SCRIPT2
//redeclaration of the same variable
var y;
if (!y) y = 'new';
alert(y); //shows New instead of Old in IE
在HTML文件中包含这2个文件
<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
你简单化了,一定发生了,所有的代码是在功能部分,提供无功雅不同范围比window.y – kennebec 2010-04-14 02:35:08
你的更新应该是一个新的问题,特别是因为它是浏览器特定的。 – 2010-04-14 04:31:58