Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

internet explorer - Redeclared javascript global variable overrides old value in IE

(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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...