ScopeChain usage example parsing _ javascript skills

Source: Internet
Author: User
Tags types of functions
This article mainly introduces the usage of ScopeChain, and analyzes the concepts, functions, and related usage skills of ScopeChain in detail based on the instance form, it has some reference value. If you need it, you can refer to the examples in this article to analyze the usage of javascript Scope Chain. We will share this with you for your reference. The details are as follows:

I have heard about the scope chain of js and have read several introductory blog posts, but I have always understood ambiguity. Recently, I carefully read the book "enlightened Javascript" and thought it was too profound. In the "time and space of code" section, I have a few words about the scope chain, the aftertaste is infinite (in fact, I still understand the ambiguity ^_^ ). Now I want to sort out my reading notes, learn from online resources, and write them down.

I. Start with a simple question

The following js Code is displayed on the page:

var arg = 1;function fucTest(arg) {  alert(arg);  var arg = 2;  //alert(arg);}fucTest(10);

What is your answer? That's right. 10 is displayed. In my understanding, the funTest function has a form parameter arg. The funTest function passes in the real parameter 10, and the alert method pops up 10, then.
Okay, the problem is coming again:

var 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, starting with the javascript Operating 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:

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, javascript 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:

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 the root of the javascript runtime environment: window object ).

Finally, the above Code is equivalent:

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. (For closures, I plan to write another study note)

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 should be recycled by the javascript engine after the data reference is null (in some cases, it will not be automatically recycled, 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), call object) many javascript phenomena can be solved by lexical scope, scope chain, 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.

I hope this article will help you design JavaScript programs.

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.