开发者

Have you ever seen this weird IE JavaScript behaviour/bug?

OK, this is driving me crazy:

First example, no problem:

<script>开发者_高级运维;

window.myvar = 150;

if (false) {
  var myvar = 3;
}

// This will popup "150"
alert(myvar)

</script>

Now, with TWO script elements:

<script>

window.myvar = 150;

</script>

<script>

if (false) {
  var myvar = 3;
}

// This will popup "undefined"
alert(myvar)

</script>

Tested with IE8.

Have you any idea why?


Inside the second example, in your second script block, myvar has been hoisted (as per the spec) to the top of the containing scope. Remember JavaScript does not have block scope, only function scope.

Therefore, var myvar (the hoisted definition that is interpreted) is going to lead to myvar being undefined when the alert() looks up myvar on the VariableObject.


That's because since javascript does scope based on function levels, your code computes/compiles/equivalent to the following:

<script>

window.myvar = 150;

</script>

<script>
var myvar;

if (false) {
  myvar = 3;
}

// This will popup "undefined"
alert(myvar)

</script>


There's a bit more too it than Alex said (even though he just referenced my article - thanks!).

If the code sequence was in the sequence it appears, "var myVar" would not get hoisted (or rather its hoisting would have no effect) because "window.myvar = 150" is defined first (moreover this wouldn't explain why the first example worked and the second one only failed in IE)

It looks like the second script is (somehow) loading before the first one - but only in IE8. You can simulate switching the tag sequence and you will see undefined alert in all browsers

var myvar;

if (false) {
  myvar = 3;
}

alert(myvar)

window.myvar = 150;


This doesn't happen to me in iOS Safari on 4.3.1, so it might be a bug in IE. However, @alex's answer may also be true as well. Ad@m


I am for hoisting, as alex said. The compiler sees that you define myvar in your block (var myvar inside if) and hoists the previously known myvar. I am not sure, whether it is bug or feature, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜