Scope rules that are common in development languages have block-level scopes and lexical scopes
The scope in which the scope can function is defined by its name, which is the area that defines a variable.
Block-level scope is to use a block structure to partition the variable access area block that {} represents the language has C-series language
Second, lexical scope is the scope of the variable, in writing the code has been determined the scope of action, independent of the runtime
Features: Split scope only functions
Variable name Promotion
function name Promotion
The declaration of a function has a higher precedence than the declaration of a variable
functionA () {}varA; alert (a);//print out the function body of a varA; functionA () {} alert (a);//print out the function body of a//but be aware of the difference between the following two words:varA=1; functionA () {} alert (a);//Print out 1<script>functionA () {}varA=1; alert (a);//Print out 1
functionTest () {bar ();//2 varFoo =function() {//variable-pointing function expressionConsole.log ("1"); } functionBar () {//function declaration function named BarConsole.log ("2"); } foo ();//1} test (); ButfunctionTest () {foo ();//ErrorBar (); varFoo =function() {//variable-pointing function expressionConsole.log ("1"); } functionBar () {//function declaration function named BarConsole.log ("2"); }} test ();
Conclusion
1, the statement will enhance
2. Only functions will limit scope
Draw Scope Chain Rules
1> all the script tags as a whole. It's a 0-level chain.
Chain in all global scope variables, functions, objects ... Are all members of the chain.
Since the declaration is promoted, the code can be adjusted before the chain is drawn, at the beginning
It is easier to write the declarations in front and draw them in the order of the drawings.
2> because only functions can qualify scopes. Therefore, a new chain is drawn on the function, and the level is n + 1
Inside the function, it is also a complete, independent scope structure
Therefore, any member defined inside the function also expands on the chain according to the rules in 1>
3> If there is a function, go ahead and draw.
Variable Search principles
In the process of running code, if you access a variable
So first on the current chain to find (unordered), if not, on the n-1 level to find
(Allows access to variables defined outside the function within the function)
So reciprocating until the 0-level chain, if the exception has not been thrown
If found, then ends the search, directly obtains the data of the variables on the chain
JavaScript function scope chain lexical scope