Iterating over properties in window object
I’ve been playing around a bit with JavaScript, and found out an interesting thing concerning property iteration in the window object in IE. In some cases, properties that are set on the window object don’t show up in the iteration.
As you probably know, setting a variable outside a function (in the so called global scope) actually writes to the window object.
-
window.X = 123;
-
window['X'] = 123;
-
X = 123;
-
var X = 123;
All of these do exactly the same: set a property X on object window.
But, when it comes to iterating window properties in IE (surprise), there seems to be a difference between the first two assignments and the last two. The code for iterating is simple; it iterates through all of the window’s properties and alerts if X is found.
-
for (var v in window) {
-
if (v == 'X') {
-
alert(v + '=' + window[v]);
-
}
-
}
With the first two assignments (the ones that write explicitly to window), the property shows up, but with the last two (where properties are implicitly assigned to window), it doesn’t. It works in Firefox, Opera, Chrome, Safari, but not in IE (not even in IE8). You can try it out here.
Why this is so, I can only guess. The property obviously exists, because window['X'] and window.X always contain the correct value. One possibility is that iterating over object properties in IE doesn’t iterate over the properties that object actually owns, but rather over a separate collection of property names. This separate collection isn’t updated properly when variables are assigned to the window object implicitly. Another possibility is that such variables exist in a global closure, and as such aren’t true members of the window object. When you access window.X and if it doesn’t exist, it’s looked up in that closure.
Interesting if not life-changing stuff. Maybe I’ll do some more research on this.
