重新声明的JavaScript全局变量覆盖IE中的旧值 [英] Redeclared javascript global variable overrides old value in IE
问题描述
(在对此进行评论后创建一个单独的问题: Javascript重新声明全局变量覆盖旧值)
我使用方括号表示法创建一个全局作用域变量,并在外部js文件中为其赋值。
在另一个js文件中,我声明了一个名称与上面刚刚创建的名称相同的变量。注意我没有分配一个值。由于这是对同一个变量的重新声明,因此旧值不应该被覆盖,如下所述: http: //www.w3schools.com/js/js_variables.asp
使用以下内容创建2个JavaScript文件:
Script1
//用方括号表示法创建全局变量
window ['y'] ='old';
Script2
//重新声明同一个变量
var y;
if(!y)y ='new';
alert(y); //在IE中显示New而不是Old
在html文件中包含这两个文件
< html>
< head>< / head>
< body>
< script type =text / javascriptsrc =my.js>< / script>
< script type =text / javascriptsrc =my2.js>< / script>
< / body>
< / html>
在Firefox和Chrome中打开此页面警告'old',这是预期的行为。然而,在IE 8中,页面实际上会提醒'新'
有关IE为何发生这种情况的任何想法?
var y
完全在第二个文件中。 这背后的理由是,既然你希望 y
是全球性的,那就把它当作全球化并已经宣布。在没有 var
前缀的情况下声明变量为全局变量的JavaScript的副作用在这种情况下对您有利。在IE8测试,这工作得很好。
编辑:至于为什么会发生这种情况,我想它只是一个组合中的错误处理IE的处理全局文件和声明提升。实际上,你应该只在一个地方声明任何变量,但特别是全局变量。遵循这个经验法则可以避免你的问题。
(creating a separate question after comments on this: Javascript redeclared global variable overrides old value)
I am creating a globally scoped variable using the square bracket notation and assigning it a value inside an external js file.
In another js file I declare a var with the same name as the one I just created above. Note I am not assigning a value. Since this is a redeclaration of the same variable the old value should not be overriden as described here: http://www.w3schools.com/js/js_variables.asp
Create 2 javascript files with the following content : 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
Include these 2 files in your html file
<html>
<head></head>
<body>
<script type="text/javascript" src="my.js"></script>
<script type="text/javascript" src="my2.js"></script>
</body>
</html>
Opening this page in Firefox and Chrome alerts 'old' which is the expected behavior. However in IE 8 the page will actually alert 'new'
Any ideas on why this happens on IE ?
If you expect y
to be global, you can just drop the var y
line altogether in your second file.
The reasoning behind this is that since you want y
to be global anyway, just treat it like its a global and already declared. JavaScript's side-effect of making variables global when declared without the var
prefix plays to your favor in this situation. Tested in IE8, this works just fine.
Edit: As to why this happens, I'd chalk it up to it just being a bug in a combination of IE's handling of globals across files and declaration hoisting. Really, though, you should only be declaring any variable, but especially a global, in one place. Your problem can be avoided by following this rule of thumb.
这篇关于重新声明的JavaScript全局变量覆盖IE中的旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!