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

Javascript 从IE8中的窗口对象访问变量不起作用,javascript,internet-explorer,Javascript,Internet Explorer,我有以下脚本: xxx = 12232; for (var j in window) { if (j==='xxx') alert('hey'); } 如果我在Chrome或Firefox中执行,我会看到警告对话框打印“嘿” 如果我在IE8中执行,我不会 显然,这是一段代码,用来证明我无法从IE8中的窗口访问变量 有人能解释一下原因吗?这段代码显示的不是你不能访问IE8中的,而是IE8中的隐式全局变量不能访问,这是完全不同的事情 您仍然可以很好地访问它: display("Creat

我有以下脚本:

xxx = 12232;
for (var j in window) { 
    if (j==='xxx') alert('hey');
}
如果我在Chrome或Firefox中执行,我会看到警告对话框打印“嘿”

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

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


有人能解释一下原因吗?

这段代码显示的不是你不能访问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);
}
|

对我来说,在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 创建隐式全局 枚举窗口属性 已完成枚举窗口属性 全球经济存在吗?真的 全局值为12232 也可通过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 创建隐式全局 枚举窗口属性 创建全球 已完成枚举窗口属性 全球经济存在吗?真的 全局值为12232 也可通过window.xxx:12232获得 隐式全局变量是一个坏主意。强烈建议不要使用它们。如果您有创建全局(而且您几乎从未创建过),请明确执行以下操作:

  • 在全局范围内使用
    var
    (在IE8上,它似乎也创建了一个不可枚举的属性)

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


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

有关详细信息,您应该看看这个。@nameIsNull是的。我确实看了一眼。不是同一个问题,但也有非常有用的信息。