Scope and function declarations in advance
"JavaScript The Definitive Guide" P57
Scope function (function scope): their function in the declaration and the function body member nested within an arbitrary function are all defined.
function Test () { var I = 0; // I are defined throughout the body of the function IF ( typeof O == 'Object' ) { var J = 0; // J are defined in the body of the entire function, just in this code segment for ( var K = 0; K <10; K ++) { // K are defined throughout the body of the function, not only in the loop the console.log (K); // output 0-9 } the console.log (K); // K has been defined, the output 10 } the console.log (J); // J been defined, but may not initialized }
JavaScript refers to the function scope are visible for all the variables declared within a function in vivo function always. This feature is called JavaScript statement in advance (hoisting), all variables in JavaScript function that is declared (but do not involve the assignment) are "ahead" to the top of the function body.
Sample code:
var scope = ", Ltd. Free Join" ; function f () { console.log (scope); // what the result is printed in the console? var scope = 'local' ; console.log (scope); // what the result is printed in the console? } F ();
Print Results:
Code analysis process:
var scope = "Global" ; function F () { the console.log (scope); // output 'undefined', rather than 'Global' var scope = 'local'; // variables assigned an initial value here, but the variable itself anywhere there is a function in vivo are defined in the console.log (scope); // output 'local' }
You might mistake the first line of the function outputs a "global", as well as local executive var statement to declare a local variable code. In actual fact, due to the nature of the function scope, local variables throughout the function body is always defined, that is, the local variables of the same name masking function body global variables. Nevertheless, only when the program execution to the var statement, the local variables will not actually be assigned. Thus, the above process is equivalent to: declare function of the variable "early" functions to the top of the body, while the remaining variables are initialized at the original location:
var scope = "Global" ; function F () { var scope; // at the top of the function of local variables declared the console.log (scope); // variable exists, but its value is 'undefined' scope = 'local'; / / where it is initialized and assigned the console.log (scope); // here we having a desired value } F ();