从IE8中的窗口对象访问变量不起作用

Zo7*_*o72 4 javascript internet-explorer

我有以下脚本:

xxx = 12232;
for (var j in window) { 
    if (j==='xxx') alert('hey');
}
Run Code Online (Sandbox Code Playgroud)

如果我在Chrome或Firefox中执行,我会打开警告对话框'嘿'.

如果我在IE8中执行,我不会.

显然,这是一段代码来证明我无法从IE8中的窗口访问变量.

有人可以解释为什么会这样吗?

T.J*_*der 7

这也就片断显示了是不是,你不能访问隐全球在IE8,它表明,在IE8中隐含的全局变量不是枚举,这是一个完全不同的事情.

你仍然可以访问它:

display("Creating implicit global");
xxx = 12232;
display("Enumerating window properties");
for (var j in window) { 
  if (j==='xxx') {
    display("Found the global");
  }
}
display("Done enumerating window properties");
display("Does the global exist? " + ("xxx" in window));
display("The global's value is " + xxx);
display("Also available via <code>window.xxx</code>: " +
        window.xxx);

function display(msg) {
  var p = document.createElement('p');
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}
Run Code Online (Sandbox Code Playgroud)

实时复制 | 资源

对我来说,在IE8上,输出:

Creating implicit global
Enumerating window properties
Done enumerating window properties
Does the global exist? true
The global's value is 12232
Also available via window.xxx: 12232

在Chrome上,全局可枚举:

Creating implicit global
Enumerating window properties
Found the global
Done enumerating window properties
Does the global exist? true
The global's value is 12232
Also available via window.xxx: 12232

隐含全局变量是一个坏主意TM.强烈建议不要使用它们.如果您必须创建一个全局(并且几乎从不这样做),请明确地执行:

  • 具有var全局范围(在IE8上,似乎也创建了不可枚举的属性)

  • 或者通过分配给window.globalname(在IE8上创建一个可枚举的属性)

我已经将这些结果(这对我来说有点奇怪)添加到我的JavaScript全局变量答案中,该答案讨论了不同种类的全局变量,因为我没有涉及那里的可枚举性.