Problem background: In writing a very simple popup interaction, defined a global variable and a method, this method is always not adjusted to this variable, get expert guidance, deliberately summed up this knowledge point;
First, variable promotion
Before ES6, JavaScript had no block-level scope (a pair of curly braces {} is a block-level scope), with only global scope and function scope. The variable elevation is about to elevate the variable declaration to the beginning of the scope where it is located.
// undefined var global = ' global '// globalfunction// Undefinedvar a = ' aaa '// AAA}fn ();
The reason is that the above printing results, is due to JS variable promotion, in fact, the above code is executed according to the following:
var // variable promotion, global scope, at this time only declared, and not assigned // undefined // The value is now assigned // Print out Global function fn () { var// variable promotion, function scope = ' aaa '; Console.log (a);} fn ();
Second, function promotion
There are two ways to create functions in JS: function declarations and function literals. function promotion only exists for function declarations! Such as:
// function F1 () {} // undefined function F1 () {} var function () {}
Only so will have the above print result, is because the function promotion in JS causes the code to actually execute according to the following:
function // function Promotion, the entire code block is promoted to the beginning of the file <br> Console.log ( F1); Console.log (F2); var function () {}
Three, the principle of summary
The function promotion is higher than the variable promotion priority! Lexical analysis Lexical analysis method:
JS Run before a similar compilation process is lexical analysis, lexical analysis is mainly three steps:
- Analysis parameters
- Declaration of the Re-analysis variable
- Analysis Function Description
The steps are as follows:
- The function generates an active object (active objects) at run-moment, called AO
- Analysis parameters
- The function receives the form parameter, adds to the Ao property, and this time the value is undefine, for example Ao.age=undefine
- Receives an argument, adds an attribute to the AO, overwrites the previous undefine
- Analyze variable declarations, such as Var age, or Var age=23;
- If the AO has no age attribute in the previous analysis parameter, the AO attribute is added as Undefine, which is ao.age=undefine
- If the AO above already has the age attribute, no modification is made
- The declaration of the parse function, if there is a functional age () {}
Assign a function to Ao.age, overwriting the value of the previous analysis
Write By:tuantuan
JS function promotion and variable promotion