Several special cases of function internal variables:
1. Global variables and local variables
function internal variable declaration with var keyword:
1 function Global () {2 var name = "Lilei" //variable declaration with VAR, still local variable, external 3}4Global () is not found; 5 Console.log (name)//Cannot Print
The function internal variable declaration does not have the var keyword:
1 function Global () {2 name = "Lilei"//is at this time global variable 3}4Global (); 5 Console.log (name)//' Lilei '
2. function internal variable Promotion
1 function Test () {2 console.log (v); 3 var v = 1; 4 }5//undefined
The above code is equivalent to
1 function Test () {2 var v = undefined; 3 Console.log (v); 4 V =1; 5 }6 test ()//undefiend
Note: The variable declaration is promoted to the top of the function, but the variable is assigned to the original position
3. Combination of function scope and variable declaration promotion
var name = ' Nelsen 'function Global () { console.log (name)}global ();//' Nelsen '
The function does not declare the name, nor is it initialized, when the function finds the global scope along the scope chain to see if there is a variable declaration with the same name, and then returns the initialized value.
1 var name = ' Nelsen '; 2 function Global () {3 console.log (name)4 var name; 5 }6 Global (); Undefined
The function outside declares name and initializes it, and the function internally declares name, and returns the default undefined
Variables for JavaScript functions