可能的重复项:
Javascript 全局变量
我应该使用 window.variable 还是 var?
问题:定义全局变量的两种方法:
-
var someVariable
全球范围; -
window["someVariable"] = “some value”;
有什么区别?
在我的测试中,这两种方式在IE中有所不同(从IE6到IE8)。(IE9 没问题)你可以在我的博客中查看它:ie-nameing3.html,或者运行以下代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Test naming in IE6</title>
<style type="text/css">
</style>
<script type="text/javascript">
window.foo = window.foo || {};
foo.eat = function(){
alert("ie6");
};
</script>
</head>
<body>
<div id="container">
</div>
<script type="text/javascript">
alert(typeof window.foo.eat);
</script>
<!-- <script type="text/javascript" src="./ie6-naming.js"></script> -->
<script>
// alert(typeof window.foo.eat);
var foo = foo || {};
alert(typeof foo.eat);
</script>
</body>
</html>
任何想法都值得赞赏!
编辑:
问题是:运行代码,你会得到两个警报:第一个显示"函数",第二个显示"未定义",为什么?
在全局范围内没有区别, 在闭包或函数中,它会有所不同:
(function() {
var a = 1;
})();
alert(a); //doesn't work
(function() {
window.a = 1; // or a = 1; (w/o the var) but not recommended (see comments)
})();
alert(a); //works!!