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

Community
  • 1
  • 1
  • And your site does not load, hence why you should use jsfiddle. What is the REAL Question/Problem here? – epascarello Jun 03 '12 at 12:04
  • @epascarello Sorry, I didn't know the link cannot load out there. What I mean is: the result of the code is : function(from the first alert) undefined(from the second alert). the latter declaration of foo overwites the former. Why? – Chengjie Mao Jun 03 '12 at 13:25

1 Answers1

0

In the global scope there's no difference, In a closure or function it would make a difference:

(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!!
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • Notice that the latter will throw a `ReferenceError` in strict mode (see https://developer.mozilla.org/en/JavaScript/Strict_mode#Converting_mistakes_into_errors). – Zeta Jun 03 '12 at 12:05