"Upgrade" of function scope in javascript, javascript
Variable upgrade of function scope in javascript
When we declare a variable with the keyword var in the function, the scope of this variable is limited to the current function.
Promotion: within a scope, no matter 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 "elevation", that is, a variable is declared With var at any position in a scope, the javascript engine will "move" these variables declared with var to the beginning of the current scope.
When talking about the "Upgrade" of javascript, I had to think that when I was studying C language in the college age, in the old C language compiler, variables in C language can only be declared and defined at the beginning of the function, variables used in a function must be declared at the beginning. No other non-declarative statements must be included before the Declaration definition. Since the c ++ language has broken this restriction, the new c compiler has no such hard limitation.
It is not a good idea to rely on the "variable escalation" mechanism such as javascript. "Function upgrade" is generally used in many cases.
Therefore, "function upgrade" can be safely used. When the place where variables are used in a scope is located before the place where variables are declared, we recommend that you do not use the "variable upgrade" phenomenon.
DEMO code for symptom escalation:
var a = 2;foo();function foo(){ a = 3; console.log(a); var a;}console.log(a);
Result:
Copyright Disclaimer: This article is an original article by the blogger. It cannot be reproduced at [http://blog.csdn.net/doctor_who2004.pdf] without the permission of the blogger.