(creating a separate question after comments on this: Javascript redeclared global variable overrides old value)
I am creating a globally scoped variable using the square bracket notation and assigning it a value inside an external js file.
In another js file I declare a var with the same name as the one I just created above. Note I am not assigning a value. Since this is a redeclaration of the same variable the old value should not be overriden as described here: http://www.w3schools.com/js/js_variables.asp
Create 2 javascript files with the following content : Script1
//create global variable with square bracket notation
window['y'] = 'old';
Script2
//redeclaration of the same variable
var y;
if (!y) y = 'new';
alert(y); //shows New instead of Old in IE
Include these 2 files in your html file
<html>
<head></head>
<body>
<script type="text/javascript" src="my.js"></script>
<script type="text/javascript" src="my2.js"></script>
</body>
</html>
Opening this page in Firefox and Chrome alerts 'old' which is the expected behavior. However in IE 8 the page will actually alert 'new'
Any ideas on why this happens on IE ?
Simplified test case:
<script>
window.foo= 1;
</script>
<script>
var foo;
alert(foo);
</script>
And yes, this absolutely is a bug in IE's JScript engine.
Why does it happen? Why does IE do any of the crazy things it does? Make an irritated noise, move on, try to avoid doing this...
If you expect y
to be global, you can just drop the var y
line altogether in your second file.
The reasoning behind this is that since you want y
to be global anyway, just treat it like its a global and already declared. JavaScript's side-effect of making variables global when declared without the var
prefix plays to your favor in this situation. Tested in IE8, this works just fine.
Edit: As to why this happens, I'd chalk it up to it just being a bug in a combination of IE's handling of globals across files and declaration hoisting. Really, though, you should only be declaring any variable, but especially a global, in one place. Your problem can be avoided by following this rule of thumb.
This is happening in IE because the line of re-declaration is setting y
to undefined. Then the line testing if y
is not set passes and y
changes to "new".
Change the second script to:
//redeclaration of the same variable
var y;
alert(y); // is undefined in IE
if (!y) y = 'new';
alert(y); //shows New instead of Old in IE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With