-2

Possible Duplicate:
Javascript global variables
Should I use window.variable or var?

Problem: Two ways to define global variables :

  1. var someVariable in global scope ;
  2. window["someVariable"] = “some value”; What's the difference ?

In my tests, the two ways a different in IE( from IE6 to IE8). (IE9 is OK) You may view it in my blog: ie-naming3.html, or run the following code:

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

Any ideas are appreciated!

EDIT:

The problem is: run the code, you get two alerts: first show you "function", but the second show you "undefined", why?

4

1 回答 1

0

在全局范围内没有区别,在闭包或函数中会有所不同:

(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!!
于 2012-06-03T12:03:23.023 回答