繁体   English   中英

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

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

我有两个脚本标记:一个用于设置环境,另一个用于读取该设置并对其执行操作。 我已将错误减少为以下内容:

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

在IE9 +,Chrome等中, 'hello world'被记录下来。 但是,在IE8中,将记录undefined 是什么赋予了?

这似乎是一个晦涩的IE8错误。

通过将所有JS放入单个脚本标签中,就可以完全避免问题。 如果您需要将它们放在单独的脚本标签中,则不确定是否有一个很好的解决方法,但是我很想听听一个。

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

它在JSFiddle中 如果在F12开发人员工具打开的情况下在IE8中将其拉起,您将看到undefined ,然后记录'hello world again'

如果这两个都是您的脚本,为什么不两次都用相同的方式定义变量(如果必须两次定义)?

<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