1 functionTestClass () {2 //define a global variable3val = 1;4 alert (val);5 alert (window.val);6 //I just added the following code7 //var val = ten;8 }9 //Call the TestClass functionTenTest =NewTestClass (); OneAlert (val);
The third line defines a global variable without VAR, and since it is a global variable, the variable becomes a property of the Window object, so the 5th and 10 rows All output 10, no objection. But look at the following code:
1 functionTestClass () {2 //define a global variable? 3val = 1;4 alert (val);5 alert (window.val);6 varval = 10;7 }8 //Call the TestClass constructor9Test =NewTestClass ();TenAlert (val);
The first alert output undefined, the second error, which is why? I just added a line var val = 10; This is because:
In fact, JavaScript as a scripting language also has so-called precompiled, all variables declared in Var, var regardless of which part will be placed at the beginning of the scope to define, the effect is actually equivalent to:
1 function TestClass () {2 var Val; 3 val = 1; 4 alert (val); 5 alert (window.val); 6 val = ten; 7 }
In this way, Val becomes a local variable. So why is the first one going to be undefined, and the second one with grammatical errors? This is because the two types of writing are still different: the first way of writing, window.val, this notation, if there is a Val attribute, then take it, if not exist, add one such attribute, because there is no initialization, so undefined; the second way of writing alert (Val); Val uses it without declaring it, which will report a syntax error. At this point, it has been explained clearly.
In fact, JavaScript is not block-level scope, but there is a function scope, see the following example:
1 function T () {2 for (var i = 0; i<4;i++) {3 4 }5 alert (i); 6 }7 alert (i);
The first alert can output 4, the second is a syntax error, which confirms what I said above, and can refer to the JavaScript authoritative guide.
JavaScript scope issues