我有以下脚本:访问从窗口对象在IE8中的变量不工作
xxx = 12232;
for (var j in window) {
if (j==='xxx') alert('hey');
}
如果我在Chrome或Firefox执行我得到的警报的对话框打印“嗨”。
如果我在IE8中执行,我不会。
显然,这是一段代码来证明我无法从IE8中的窗口访问变量。
有人可以解释为什么吗?
我有以下脚本:访问从窗口对象在IE8中的变量不工作
xxx = 12232;
for (var j in window) {
if (j==='xxx') alert('hey');
}
如果我在Chrome或Firefox执行我得到的警报的对话框打印“嗨”。
如果我在IE8中执行,我不会。
显然,这是一段代码来证明我无法从IE8中的窗口访问变量。
有人可以解释为什么吗?
这段代码显示的不是您不能访问IE8中的implicit global,它显示IE8中的隐式全局变量不是enumerable,这是完全不同的事情。
,您仍然可以访问它只是罚款:
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
在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 global variables回答说不同种类的全局变量,因为我没有涉及到那里的枚举。
+1。 IE8方式中有趣的见解:) –
@ T.J克罗德非常感谢你的明确解释 – Zo72
你应该看看这个更多信息[Javascript全局变量](http://stackoverflow.com/questions/4862193/javascript-global-variables)。 – AlexandruSerban
@nameIsNull yep。我确实看了一下。不是同一个问题,而是非常有用的信息。 – Zo72