Zo72
Zo72

Reputation: 15305

accessing a variable from window object in IE8 does not work

I have the following script:

xxx = 12232;
for (var j in window) { 
    if (j==='xxx') alert('hey');
}

If I execute in Chrome or Firefox I get the alert-dialog printing 'hey'.

If I execute in IE8 I don't.

Obviously,this is a snippet of code to prove that I can not access a variable from window in IE8.

Can somebody explain why that is ?

Upvotes: 4

Views: 3985

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

What that snippet shows isn't that you can't access the implicit global in IE8, it shows that implicit globals in IE8 are not enumerable, which is a totally different thing.

You can still access it just fine:

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);
}

Live Copy | Source

For me, on IE8, that outputs:

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

On Chrome, the global is enumerable:

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

Implicit globals are a Bad IdeaTM. Strongly recommend not using them. If you have to create a global (and you almost never do), do it explicitly:

  • With a var at global scope (which, on IE8, seems to also create a non-enumerable property)

  • Or by assigning to window.globalname (which, on IE8, creates an enumerable property)

I've added these results (which are, to me, a bit odd) to my JavaScript global variables answer that talks about different kinds of globals, since I hadn't touched on enumerability there.

Upvotes: 7

Related Questions