Javascript Running Mechanism

Source: Internet
Author: User
Document directory
  • Compilation process
  • Execution Process
  • Summary

Start with a simple question:

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

The output result isundefinedThis phenomenon is called "pre-resolution": the JavaScript engine will first parse the VaR variables and function definitions. The code is executed only after the pre-resolution is complete. If a document stream contains multiple script code segments (JavaScript code separated by SCRIPT tags or imported JS files), the running sequence is:

Step1. read the first code segment step2. perform syntax analysis. If there is a mistake, a syntax error is reported (for example, the parentheses do not match) and jump to step5step3. perform "pre-resolution" on VaR variables and function definitions (errors will never be reported, because only correct declarations are parsed) Step 4. Execute the code segment. If there is an error, an error is returned (for example, the variable is not defined) step 5. If there is another code segment, read the next code segment and repeat Step 2. end

The above analysis can already explain many problems, but I always feel that there is something missing. For example, in step 3, what is "pre-resolution? See the following example in Step 4:

<script type="text/javascript">    alert(i); // error: i is not defined.    i = 1;</script>

Why does the first sentence cause errors? In JavaScript, can variables be left unspecified?

Compilation process

Time is like a white horse, and the bookcase opens like a different world-like "Compilation Principle". The familiar and unfamiliar blank spaces have such notes:

For traditional compilation 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, they can start to explain and execute.

To put it simply, lexical analysis converts the character stream (char stream) to the token stream (for examplec = a - b;Convert:

NAME "c"EQUALSNAME "a"MINUSNAME "b"SEMICOLON

The above is just an example. For more information, see lexical analysis.

Chapter 1 of the Javascript authoritative guide, about the lexical structure, also described in the ECMA-262. Lexical structure is the basis of a language and is easy to grasp. The implementation of lexical analysis is another field of research.

It can be analogous to natural languages. lexical analysis is a one-to-one hard translation. For example, a piece of English is translated into Chinese one by one. What we get is a bunch of Mark streams, which are hard to understand. Further translation requires syntax analysis. It is a syntax tree of conditional statements:

When constructing a syntax tree, if you find that it cannot be constructed, for exampleif(a { i = 2; }The system reports a syntax error and ends parsing the entire code block. This is the step at the beginning of this article.

After the syntax tree is constructed through syntax analysis, the translated sentences may be ambiguous. Further semantic check is required. For traditional strong-type languages, the main part of semantic check is type check, for example, whether the real parameters and form parameters of the function match. For a weak language, this step may not be available (limited energy, no time to look at the JS engine implementation, not sure if the JS engine has a semantic check ).

From the above analysis, we can see that for the JavaScript engine, there must be lexical analysis and syntax analysis, followed by 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.

The above compilation process cannot further explain the "pre-resolution" at the beginning of the article. We have to carefully explore the execution process of JavaScript code.

Execution Process

Zhou aimin carefully analyzed the second part of "javascript language essence and programming practices. Below are some of my insights:

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. Javascript uses 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. In fact, it can only be said that the scope mechanism of JS is very close to lexical scope.

When the JS engine executes each function instance, it creates an execution environment (Execution context ). Execution context contains a call object, which is a scriptobject structure, 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: 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 ). Scriptobject is a function-related static system, consistent with the life cycle of the function instance.

Lexical scope is the scope mechanism of JS. You also need to understand its implementation method. This is scope chain ). Scope chain is a name lookup mechanism. First, it is searched in the scriptobject of the current execution environment. If it is not found, it will be searched in upvalue to the parent scriptobject, always lookup to the global object ).

When a function instance is executed, a closure is created or associated with it ). Scriptobject is used to statically store function-related variable tables. Closure dynamically stores these variable tables and their running values during the execution period. Closure may have a longer life cycle than function instances. Function instances are automatically destroyed when the active reference is empty. Closure is recycled by the JS engine after the data reference is empty (in some cases, it is not automatically recycled, memory leakage ).

Don't be intimidated by the above nouns. Once you understand the execution environment, calling objects, closures, lexical scopes, and scope chains, many JS language phenomena can be solved.

Summary

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

The so-called "pre-resolution" in step 3 is actually completed in the syntax analysis phase of step 2 and stored in the syntax tree. When executed to a function instance, vardelcs and funcdecls are copied from the syntax tree to the scriptobject in the execution environment.

In step 4, the undefined variable means that it cannot be found in the scriptobject variable table, and the JS engine will search for it along the upvalue of scriptobject. If not, write operationsi = 1;Finally, it is equivalentwindow.i = 1;Adds an attribute to the window object. For read operations, if the scriptobject that is traced back to the global execution environment cannot be found, a runtime error will occur.

After understanding it, the sky is clear and the fog is blooming.

Finally, leave a question to everyone:

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

What is alert output?

References
  • Zhou aimin's JavaScript language essence and programming practices (I suggest you read the second part carefully. The book is always very readable)
  • Implement a script engine (the engine is not as esoteric as we think)
  • Javascript closures (recommended)
  • Hax: a brief description of the Javascript scope mechanism (concise)
Descending Order

This article was written more than a week ago. The javascript language is a bit like studying quantum mechanics in college. I just thought it was clear and I was confused again. After being confused, I will study it carefully. When everything becomes clear like a month, suddenly an idea and a thinking trap will fall into the confusion. However, whether confused or clear, keep the learning mentality clearer.

From: http://lifesinger.org/blog/2009/01/javascript-run-mechanism/

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.