[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.