Js scope chain

Source: Internet
Author: User
Tags types of functions

1. Scope
Javascript scopes can be summarized in one sentence: two types of scopes (global, function) and three scope chains.
You need to understand the following two concepts before understanding them:
1) JavaScript is a lexical scope. When a function is defined, its scope chain is saved as the internal state of the function.
2) When a function is defined, although the scope chain is determined, the attributes in the scope chain are not determined.
Two types of scopes:
1) global scope -- the variable is the property of the window object (in the default browser environment ). <Scope chain: window>
2) function scope-sequence of Variable Search (I .e. scope chain) <Current call object --... -- window object>
A special scope chain:
Event processing Code defined by the HTML attribute: <call object of the anonymous function -- current node -- parent node --... -- window object>
Bytes --------------------------------------------------------------------------------------------------------

2. this
Can be simply summarized as: "this" is a keyword not a property of any object, that refer to one object depending on the scope. in the global scope, it refers to the window object. in the function scope it refers to the object that has the function as its property.

Example: Why is this reference in the event processing function used to register the event element when the original event is registered?
Cause-the original event registration essentially uses the event handler as an attribute (method) of this element ).

A problem that is still confusing till now:
Function outer (){
Function inner (){
Alert (this );
}();
}
----------------------------- The result is window -------------------------------------------------
Why "this" refer to the window object, the function inner is not the property of window .-_-
Conjecture: Does this reference window by default when a function is not used as an attribute of other objects?
Bytes ----------------------------------------------------------------------------------------------------
10/9
By asking about Arrix, I guess it is correct.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Js Code ar arg = 1;
Function funcTest (){
Alert (arg );
Var arg = 2;
}
Arg = 10;
FuncTest ();
Ar arg = 1;
Function funcTest (){
Alert (arg );
Var arg = 2;
}
Arg = 10;
FuncTest ();

What is the answer? If it was five years ago, I would never think about it again, or 10! What else do you think about such a simple question? In my understanding, the funTest function is a non-parametric function. The function internally calls the external (global) variable arg through the alert method. Before the function is executed, if the value of arg is 10 and the value of arg is 2, the value is 10.
Is it actually 10? Yes or no?
Test Result: "undefined" is displayed.
2. Understand the scope chain from javas

Refer to Running Mechanism
1. js running sequence
If a document stream contains multiple script code segments (JavaScript code separated by script tags or imported js files), the running sequence is:
Step 1. Read the first code segment (the js execution engine does not execute the program in one row, but analyzes and executes the program in one row)
Step 2. Perform syntax analysis. If there is a mistake, a syntax error is reported (for example, parentheses do not match), and jump to Step 5.
Step 3. Perform "pre-resolution" on var variables and function definitions (no error will be reported because only the correct declaration is parsed)
Step 4. Execute the code segment. If there is an error, an error is returned (for example, the variable is undefined)
Step 5. If there is another code segment, read the next code segment and repeat Step 2.
Step 6. End
The above analysis is clear enough. The red font in step 2, step 3, and step 4 may be a blind spot for new users to understand, especially the "pre-resolution" in step 3 ", if you don't know what pre-resolution is, you always feel unreliable. In step 4, errors are often reported. For example:
Js Code function funcTest (){
Alert (arg );
Var arg = 2;
}
FuncTest ();
Function funcTest (){
Alert (arg );
Var arg = 2;
}
FuncTest ();
When the above code is executed, "undefined" is displayed. That is to say, arg is not defined. Can js variables be defined without any need?
2. syntax analysis and pre-resolution"
(1) starting from the compilation process of interpreted language
As we all know, javas

Explain is an interpreted language, which is different from c # and java compiling languages. For traditional compiled languages, the compilation steps include lexical analysis, syntax analysis, semantic check, code optimization, and byte generation. However, for interpreted languages, after obtaining the syntax tree through lexical analysis and syntax analysis, you can start the interpretation and execution.
A. Lexical Analysis
To put it simply, lexical analysis converts the character stream (char stream) to the token stream ).
However, this conversion process is not as simple as a single sentence. We can try to use pseudo code to understand a simple program:

The conversion of code var result = x-y; can be roughly expressed as follows:

NAME "result"
EQUALS
NAME "x"
MINUS
NAME "y"
SEMICOLON

B. syntax analysis
To put it simply, syntax analysis is to construct a valid syntax analysis tree, which intuitively shows the process of derivation.
So what is the syntax analysis tree? Simply put, it is the description of the program derivation process. However, for more information about what a syntax tree is, see this article.
C. Others
After the syntax analysis tree is constructed, further semantic checks may be required. For traditional strong-type languages, the main part of semantic check is type check, for example, whether the real parameters and parameter types of functions match.
Conclusion: from the above analysis, we can see that for the javascript engine, there must be lexical analysis and syntax analysis, and there may be other steps such as semantic check and code optimization, after these compilation steps are completed (any language has a compilation process, but the explanatory language has not compiled the code into binary code), the code will start to be executed.
(2) Execution Process
A. javascript scope Mechanism
After compilation, the javascript code has been translated into a syntax tree and will be immediately executed according to the syntax tree.
For further execution, we need to understand the javascript scope mechanism: lexcical scope ). In general, the scope of javascript variables is determined during definition rather than execution. That is to say, the lexical scope depends on the source code and can be determined by the compiler through static analysis, therefore, lexical scopes are also called static scopes ). However, it should be noted that the semantics of with and eval cannot be implemented only through static technology, so it can only be said that the javascript scope mechanism is very close to the lexical scope ).
When executing each function instance, the javascript engine creates an execution environment (execution context ). The execution environment contains a call object. The call object is a scriptObject structure (scriptObject is a static system related to the function, consistent with the life cycle of the function instance ), it is used to save the syntax analysis structures of the internal variable table varDecls, built-in function table funDecls, parent Reference List upvalue, and so on (note that varDecls and funDecls are obtained in the syntax analysis phase, and save it in the syntax tree. When the function instance is executed, the information is copied from the syntax tree to scriptObject ).
B. Implementation of javascript scope Mechanism
Lexical scope is the scope mechanism of javascript. You also need to understand its implementation method, that is, scope chain ). The scope chain is a name lookup mechanism. It is first searched in the scriptObject of the current execution environment. If it is not found, it will be searched in the parent scriptObject following upvalue, always lookup to the global object ).
Now let's look back at the second question:

Js Code var arg = 1;
Function funcTest (){
Alert (arg );
Var arg = 2;
}
Arg = 10;
FuncTest ();
Var arg = 1;
Function funcTest (){
Alert (arg );
Var arg = 2;
}
Arg = 10;
FuncTest ();
When the funcTest function is executed, it enters the corresponding scope of funcTest. When the js engine is executed, when it is used for the variable name or function name, the system first searches for variables or functions in the current scope (that is, the scope corresponding to funcTest) (obviously, the arg variable is defined as var arg = 2 in the scope corresponding to funcTest. Therefore, the parameters of the alert method use the arg of the current scope. However, because arg is defined after the alert method, so the default value of arg variable is undefined ). Of course, if it is not found, it will be searched in the upper-level scope, and so on (the scope can continue to javas

Worker runtime environment root: window object ).
Finally, the above Code is equivalent:

Js Code var arg = 1;
Function funcTest (){
Var arg; // default value: undefined
Alert (arg );
Arg = 2;
}
Arg = 10;
FuncTest ();
Var arg = 1;
Function funcTest (){
Var arg; // default value: undefined
Alert (arg );
Arg = 2;
}
Arg = 10;
FuncTest ();
C. closure)
When a function instance is executed, a closure is created or associated.
ScriptObject is used to statically store function-related variable tables. The closure dynamically stores these variable tables and their running values during the execution period;
The lifecycle of a closure may be longer than that of a function instance. Function instances are automatically destroyed when the active reference is empty;
The closure must wait until the data reference is null

Memory engine recycling (in some cases, it does not automatically recycle, leading to memory leakage ).
Ps: There are many terms for the "execution Process" section, but don't be intimidated by them. Once you understand the execution environment (execution context) and call object (callobject) many javascript phenomena can be solved by lexical scope, scopechain, and closure.
Iii. Conclusion
Through the analysis in the second section, compare the judgment made by the author in the first section (do you also think that the author's analysis and conclusions are naive (even if sometimes the results happen to be correct !)?! It's not generally superficial, ^ _ ^). You will find that there are so many "xuanjicang" in javascript, but it's easy to understand and be proficient? Let's talk about it first.

 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.