Infallible Logic

31Jan/112

[Javascript] Internet Explorer namespacing

We just ran into a ridiculous bug here that doesn't seem to be mentioned in many places. The best post I've seen about it is here:

Basically there's a bug on how IE's JScript expands global variable names.

If one does
for(foo in {'a':'b', 'c':'d'}) { alert(foo); }
One gets the expected alerts for 'a' and 'c'.

However, if one chooses to use the variable name 'item', as such:
for(item in {'a':'b', 'c':'d'}) { alert(item); }

One gets an error, saying the 'object does not support this action'. Digging a bit deeper, this happens not only with the word 'item', but any property of the window object, or its prototype (any property to which it responds, like toString). It seems IE JScript is expanding 'item' to 'window.item', and what results is 'for(window.item in ...', which is wrong.

This does not happen if scoping with the 'var' keyword, since then the engine knows it's a local variable, not a property of the global object.

So essentially, if you don't create a variable in a local scope with the 'var' keyword, and it's a variable that exists in the window object or its prototype, it will look for it in the window object instead of your local scope. So keep that in mind when creating loops and whatnot that may not necessarily require you to use the var keyword.

Comments (2) Trackbacks (0)
  1. This is just the default scope at work — that’s why the author of those examples can call window.alert() without the window prefix! Other browsers don’t seem to have a window.item property.

  2. Yeah, you’re correct. I was dumb a year ago!

    I’m still kinda dumb now.

    IE is still the only time I’ve run into this kind of thing when ‘accidentally’ overriding a window-scope level object, though. I guess I haven’t really gone out of my way to test anything, though. Chrome, at least, appears to gracefully just ‘ignore’ overriding of crucial window elements.


Leave a comment

No trackbacks yet.