A brief analysis of JavaScript running mechanism

Source: Internet
Author: User
Tags closure object object script tag

Start with a simple question:

<script type= "Text/javascript" >     alert (i);   var i = 1;     </script>

The output is undefined, which is called "Pre-parsing": The JavaScript engine prioritizes the var variable and the function definition. The code is not executed until pre-parsing is complete. If a document flow contains more than one script snippet (the JS code separated by the script tag or the introduced JS file).

The order of operation is:

Step1. Read in the first code snippet
Step2. Do grammatical analysis, error is reported grammatical errors (such as parentheses mismatch, etc.), and jump to Step5
Step3. "Pre-parsing" of var variables and function definitions (never error, because only correct declarations are parsed)
Step4. Execute code snippet with error (e.g. variable undefined)
Step5. If there is a next code snippet, read the next code snippet and repeat Step2
Step6. End

The above analysis has been able to explain a lot of problems, but the old feel the lack of something. such as STEP3, "pre-analytic" What is the matter? And STEP4, look at the following example:

<script type= "Text/javascript" >     alert (i);//ERROR:I is not defined.     i = 1;     </script>

Why does the first sentence lead to an error? In JavaScript, can variables not be undefined?

Compilation process

Time, such as White Horse gap, the bookcase next opened Huangrugeshi-like "compiling principle", familiar and unfamiliar blank place has such notes:

For traditional compiled languages, the compilation steps are: Lexical analysis, parsing, semantic checking, code optimization, and byte generation.

But for an interpreted language, the syntax tree is obtained through lexical analysis and parsing, and it can begin to explain the execution.

To put it simply, lexical analysis converts a character stream (char stream) into a tick stream (token stream), such as C = a–b;

Name "C" EQUALS  name "a" minus  name "B" semicolon

Above is just an example, see Lexical Analysis for further information.

The 2nd chapter of the JavaScript authoritative guide is about lexical structure (Lexical Structure), which is also described in ECMA-262. Lexical structure is the basis of a language, it is easy to grasp. As for the realization of lexical analysis that is another area of study, not explored here.

can take natural language to analogy, lexical analysis is a one-to-one hard translation, such as a paragraph of English, Word to Chinese, get a bunch of tick flow, it is difficult to understand. Further translation, it is necessary to parse the syntax, is a conditional statement of the syntax tree:

When constructing a syntax tree, if it is found to be unable to construct, such as if (a {i = 2;}, the syntax error is reported and the parsing of the entire code block is ended, which is the STEP2 at the beginning of this article.

After parsing the syntax tree, the translated sentences may be ambiguous, and further semantic checks are required. For traditional strongly typed languages, the main part of the semantic check is type checking, such as whether the function's arguments and formal parameter types match. For weakly typed languages, this step may not be possible (limited effort, no time to see the JS engine implementation, not sure whether there is a semantic check in the JS engine this step).

As can be seen from the above analysis, for the JavaScript engine, there must be lexical analysis and parsing, and then there may be semantic inspection, code optimization and other steps, and so on after these compilation steps (any language has a compilation process, only the interpretation of the language is not compiled into binary code), To start executing the code.

The above compilation process, or can not be more in-depth explanation of the beginning of the article "Pre-parsing", we also have to carefully explore the next JavaScript code execution process.

Execution process

Greatlypraised in the second part of the JavaScript language essence and programming practice, there is a very careful analysis of this. Here are some of my insights:

By compiling, the JavaScript code has been translated into a syntax tree and then executed immediately following the syntax tree.

The further execution process requires an understanding of the scope mechanism of JavaScript, which uses lexical scopes (lexcical scope). In layman's parlance, the scope of a JavaScript variable is determined at the time of definition rather than execution, meaning that the lexical scope depends on the source code, and the compiler can determine it through static analysis, so the lexical scope is also called the static scope. However, it is important to note that the semantics of with and Eval cannot be achieved only through static techniques, in fact, only the scope mechanism of JS is very close to lexical scope.

The JS engine creates an execution environment (execution context) when each instance of a function is executed. The execution context contains a Call object (called object), which is a scriptobject structure that holds the internal variable table vardecls, the inline function table Fundecls, Parent reference list Upvalue such as parsing structures (note: Information such as VARDECLS and FUNDECLS are available in the parsing phase and are saved in the syntax tree. When the function instance executes, the information is copied from the syntax tree to the ScriptObject. ScriptObject is a set of static systems associated with a function that is consistent with the life cycle of a function instance.

Lexical scope is the scope mechanism of JS, also need to understand its implementation method, this is the scope chain (scope chain). Scope chain is a name lookup mechanism that is first searched for in the scriptobject of the current execution environment and is not found, and then looks in the Upvalue to the parent scriptobject, always looking to the global calling object Object).

When a function instance executes, it is created or associated to a closure (closure). ScriptObject is used to statically save the variable tables associated with the function, and closure dynamically saves the variable tables and their running values during the execution period. The life cycle of the closure is likely to be longer than the function instance. The function instance is automatically destroyed when the active reference is empty, and the closure waits for the data reference to be empty, which is recycled by the JS engine (in some cases it is not automatically recycled, resulting in a memory leak).

Don't be intimidated by a bunch of nouns above, once you understand the concepts of execution environment, calling object, closure, lexical scope and scope chain, many phenomena of JS language can be solved.

Summary

At this point, the question at the beginning of the article can be explained very clearly:

The so-called "pre-parsing" in Step3 is actually done in the STEP2 parsing phase and stored in the syntax tree. When executed to a function instance, Vardelcs and Funcdecls are copied from the syntax tree to the scriptobject of the execution environment.

In Step4, the undefined variable means that the ScriptObject cannot be found in the variable table, and the JS engine looks up along the ScriptObject upvalue, if none are found, for the write operation i = 1; In the end, it will be equivalent to WINDOW.I = 1; A new property has been added to the Window object. For read operations, run-time errors are generated if they are not found on the scriptobject that are traced back to the global execution environment.

Understanding, the fog scattered flowers, the sky is clear.

Finally, leave a question for everyone:

<script type= "Text/javascript" >     var arg = 1;     function foo (ARG) {     alert (ARG);     var arg = 2;     }     Foo (3);     </script>

What is the output of alert, please?

A brief analysis of JavaScript running mechanism

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.