简体   繁体   English

为什么我已经定义的全局变量被IE8中的另一个var语句覆盖?

[英]Why is my already-defined global variable being overwritten by another var statement in IE8?

I have two script tags: one to set up my environment, and another to read that setup and act upon it. 我有两个脚本标记:一个用于设置环境,另一个用于读取该设置并对其执行操作。 I've reduced the bug to the following: 我已将错误减少为以下内容:

<script>
    window.myVar = 'hello world';
</script>
<script>
    var myVar;
    console.log(window.myVar); // Should be 'hello world'
</script>

In IE9+, Chrome, etc. 'hello world' gets logged. 在IE9 +,Chrome等中, 'hello world'被记录下来。 In IE8, however, undefined gets logged instead. 但是,在IE8中,将记录undefined What gives? 是什么赋予了?

This seems to be an obscure IE8 bug. 这似乎是一个晦涩的IE8错误。

By simply putting all of the JS into a single script tag, you avoid the problem entirely. 通过将所有JS放入单个脚本标签中,就可以完全避免问题。 Not sure of a great workaround if you need them to be in separate script tags, but I'd love to hear one. 如果您需要将它们放在单独的脚本标签中,则不确定是否有一个很好的解决方法,但是我很想听听一个。

<!-- This triggers the bug in IE8. -->
<script>
    window.myVar = 'hello world';
</script>
<script>
    var myVar;
    console.log(window.myVar); // Should be 'hello world'
</script>


<!-- This does not trigger the bug in IE8. -->
<script>
    window.myOtherVar = 'hello world again';
    var myOtherVar;
    console.log(window.myOtherVar); // Should be 'hello world again'
</script>

Here it is in a JSFiddle . 它在JSFiddle中 If you pull it up in IE8 with the F12 developer tools open, you'll see undefined and then 'hello world again' logged. 如果在F12开发人员工具打开的情况下在IE8中将其拉起,您将看到undefined ,然后记录'hello world again'

If these are both your scripts, why not define the variable (if you must define it twice) the same way both times? 如果这两个都是您的脚本,为什么不两次都用相同的方式定义变量(如果必须两次定义)?

<script>
 window.myVar = 'hello world';
</script>
<script>
 window.myVar = window.myVar || undefined;
 console.log(window.myVar); // Should be 'hello world'
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM