Variables, Scope, and Memory(Chapter 4 of Professional JavaScript® for Web Developers 2nd Edition)
JavaScript ’ s lack of block - level scopes is a common source of confusion.
1 <html>
2 <head>
3 <script type="text/javascript">
4
5 console.log("-----------------scope-------------------");
6 if(true)
7 {
8 var test = "Hello";
9 }
10 console.log(test);
11
12 for(var i=0; i<10; i++)
13 {
14
15 }
16
17 console.log(i);
18 </script>
19 </head>
20 <body>
21 </body>
22 </html>
2 <head>
3 <script type="text/javascript">
4
5 console.log("-----------------scope-------------------");
6 if(true)
7 {
8 var test = "Hello";
9 }
10 console.log(test);
11
12 for(var i=0; i<10; i++)
13 {
14
15 }
16
17 console.log(i);
18 </script>
19 </head>
20 <body>
21 </body>
22 </html>
When a variable is declared using var , it is automatically added to the most immediate context available. In a function, the most immediate one is the function ’ s local context; in a with statement, the most immediate is the function context. If a variable is initialized without first being declared, it gets added to the global context automatically, as in this example:
1 <html>
2 <head>
3 <script type="text/javascript">
4
5 function add(num1, num2)
6 {
7 result = num1+num2;
8 return result;
9 }
10 console.log(add(10, 20));
11 console.log(result); //30
12 </script>
13 </head>
14 <body>
15 </body>
16 </html>
2 <head>
3 <script type="text/javascript">
4
5 function add(num1, num2)
6 {
7 result = num1+num2;
8 return result;
9 }
10 console.log(add(10, 20));
11 console.log(result); //30
12 </script>
13 </head>
14 <body>
15 </body>
16 </html>
Not all objects in IE are native JavaScript objects. Objects in the Browser Object Model (BOM) and Document Object Model (DOM) are implemented as COM (Component Object Model) objects in C++, and COM objects use reference counting for garbage collection.