重新声明的 javascript 全局变量会覆盖 IE 中的旧值 [英] Redeclared javascript global variable overrides old value in IE

查看:17
本文介绍了重新声明的 javascript 全局变量会覆盖 IE 中的旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(在对此发表评论后创建一个单独的问题:Javascript 重新声明全局变量覆盖旧值)

(creating a separate question after comments on this: Javascript redeclared global variable overrides old value)

我正在使用方括号表示法创建一个全局范围的变量,并在外部 js 文件中为其分配一个值.

I am creating a globally scoped variable using the square bracket notation and assigning it a value inside an external js file.

在另一个 js 文件中,我声明了一个与我刚刚在上面创建的同名的 var.注意我没有赋值.由于这是对同一变量的重新声明,因此不应按照此处所述覆盖旧值:http://www.w3schools.com/js/js_variables.asp

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

创建 2 个 javascript 文件,内容如下:脚本1

Create 2 javascript files with the following content : Script1

//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 文件中包含这 2 个文件

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>

在 Firefox 和 Chrome 中打开此页面会提示旧",这是预期的行为.但是在 IE 8 中,页面实际上会提醒新"

关于为什么在 IE 上会发生这种情况的任何想法?

Any ideas on why this happens on IE ?

推荐答案

如果您希望 y 是全局的,您可以将 var y 行完全删除在您的第二个文件.

If you expect y to be global, you can just drop the var y line altogether in your second file.

这背后的原因是因为无论如何你都希望 y 是全局的,只要把它当作一个全局的并且已经声明就可以了.在这种情况下,JavaScript 在没有 var 前缀的情况下使变量成为全局变量的副作用对您有利.在 IE8 中测试,这工作得很好.

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.

至于为什么会发生这种情况,我将其归结为 IE 跨文件处理全局变量和声明提升的组合中的一个错误.但是,实际上,您应该只在一个地方声明任何变量,尤其是全局变量.遵循这条经验法则可以避免您的问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆