Variable elevation of function scope in JavaScript
When we declare a variable within a function with the keyword VAR, the scope of this variable is limited to the current function.
Ascension: Within a scope, regardless of where a variable is declared with Var, the variable belongs to the current entire scope and can be accessed anywhere in the current scope. In JavaScript, this behavior/phenomenon is called "Ascension", where a variable is declared at any place in a scope with Var, and the JavaScript engine "moves" the variable declared with Var to the beginning of the current scope.
Speaking of JavaScript This "ascension" phenomenon, had to think of college time to learn C language, the old C compiler, C language, variables can only be declared at the beginning of the function and definition, in the function to use the variable must be declared at the beginning of the definition, The declaration definition cannot have any other statements that are not declared defined before. Since the C + + language has broken this limit, the new compiler does not have this hard limit.
Relying on JavaScript as a "variable elevation" mechanism is not a good idea. "Function Promotion" we generally use more.
Therefore, "function ascension" is safe to use, when the use of variables in a scope where the variable is in the declaration of the variable, and the "Variable Ascension" phenomenon, we had better not use.
Elevation Symptom code Example:
var a = 2;
Foo ();
function foo () {
a = 3;
Console.log (a);
var A;
}
Console.log (a);
Results: