JavaScript from definition to execution, those things you should know

Source: Internet
Author: User
Tags define function

JavaScript from definition to execution, JS engine has done a lot of initialization in the implementation layer, so before learning the JS engine working mechanism, we need to introduce several related concepts: execution environment stack, global object, execution Environment, variable object, activity object, scope and scope chain, etc. These concepts are the core components of the JS engine's work. The purpose of this article is to explain each concept in isolation, instead of analyzing it through a simple demo, explaining every detail of the JS engine from definition to execution, and the role that these concepts play in.

 var  x = 1; //  defines a global variable x  function    A (y) { var  x = 2; //    function  B (z) {//  define an intrinsic function B  console.log (x+y+< Span style= "color: #000000;"   >Z);  return  B; //  Returns a reference to function B    var  C = A (1); //  execute a, return b  C (1); //  Execute function b  

This demo is a closure, the execution result is 4, below we will be divided into global initialization , execute function A, execute function B three stages to analyze the JS engine working mechanism:

First, global initialization

The JS engine needs to complete the following three initialization tasks as it enters an executable code:

First, create a global object that has only one copy globally, and its properties can be accessed anywhere, and its existence accompanies the entire life cycle of the application. When the global object is created, the common JS object, such as Math,string,date,document, is used as its property. Since this global object cannot be accessed directly by name, there is another property window, which points to itself so that the global object can be accessed through window. The general structure for simulating global objects with pseudo-code is as follows:

// Create a Global object var globalobject = {     math:{},    string:{},    date:{},    //DOM operation     ...    window:this// Let Window property point to itself }

The JS engine then needs to build an execution environment stack (execution context stack), while also creating a global execution Environment (execution context) EC and pressing the global execution environment EC into the execution environment stack. The role of the execution environment stack is to ensure that the program is executed in the correct order. In JavaScript, each function has its own execution environment, and when a function is executed, the execution environment of the function is pushed to the top of the execution environment stack and gets execution. When this function is completed, its execution environment is removed from the top of the stack and the execution is given back to the execution environment. We use pseudo-code to simulate the relationship between the execution environment stack and the EC:

var // defines an execution environment stack, similar to an array var EC = {};   // Create an execution space, // The ECMA-262 specification does not explicitly define the data structure of the EC, which you can understand as a space allocated in memory  // Enter function, press into the execution Environment Ecstack.pop (EC);  // after the function returns, delete the execution environment

Finally, the JS engine also creates a global variable object associated with the EC (Varibale object) Vo,  , which points to the global object, VO contains not only the original properties of the global object, but also the globally defined variable x and function A, at the same time, At the time of defining function A, an internal property scope is added for a, and the scope is pointed to VO. Each function, when defined, creates a scope property associated with it, and the scope always points to the environment in which the function is defined. The ecstack structure at this point is as follows:

Ecstack = [   // execution Environment stack    EC (G) = {   // Global Execution Environment        // define global variable Object             // contains the original properties of the global object            // define variable x            function // define function A             This // define scope for a and assign a value of Vo itself         }    }];

Second, executive function a

When execution enters a (1), the JS engine needs to complete the following tasks:

First, the JS engine creates the execution environment EC for function A, then the EC pushes the top of the execution environment stack and gets the execution right. There are two execution environments in the execution environment stack, namely the global execution environment and the function a execution environment, the execution environment of A is at the top of the stack, and the global execution environment is at the bottom of the stack. Then, create the scope chain of function A (scope Chain), in JavaScript, each execution environment has its own scope chain for identifier resolution, and when the execution environment is created, its scope chain is initialized to the objects contained in the scope of the currently running function.

The JS engine then creates an active object of the current function (Activation object) AO, where the active object plays the role of the variable object, except in the function (you can assume that the variable object is a general concept, and that the active object is a branch of it). The AO contains the formal parameters of the function, the arguments object, the This object, and the definition of local variables and intrinsic functions, and then the AO is pushed to the top of the scope chain. It is important to note that when defining function B, the JS engine also adds a scope property to B and points to the environment where function B is defined, and the environment in which function B is defined is the active object AO of a, and AO is at the front of the list, because the linked list has the characteristics Therefore, the scope of function B points to the entire scope chain of a. Let's look at the ecstack structure at this time:

Ecstack = [//Execution Environment StackEC (A) = {//the execution environment of a[Scope]:vo (G),//Vo is a global variable objectAO (A): {//creating the active object for function aY:1, x:2,//defining local Variables xB:function(){...},//defining function BB[[scope]] = This;//This refers to the AO itself, while AO is at the top of the Scopechain,so B[[scope]] points to the whole scope chainArguments:[],//The arguments that we normally access in our functions is the arguments in the AO.            This :Window//the This in the function points to the caller window object}, Scopechain:<ao (A),a[[scope]]>//list initialized to A[[scope]], and then add AO to the scope chainat the top of this time A's scope chain: AO (a)->vo (G) }, EC (G)= {//Global Execution EnvironmentVO (G): {//creating a global variable object...//contains the original properties of the global objectx = 1;//define variable xA =function(){...};//define function AA[[scope]] = This;//definition A of scope,a[[scope]] = = VO (G)         }    }];

Third, executive function b

After function A is executed, a reference to B is returned, assigned to the variable C, execution C (1) is equivalent to B (1), and the JS engine needs to do the following:

First, as in the above, create the execution Environment EC for function B, then the EC pushes the top of the execution environment stack and gets the execution right. There are two execution environments in the execution environment stack, namely the execution environment of the global execution environment and function B, the execution environment of B is at the top of the stack, and the global execution environment is at the bottom of the stack. (Note: When function A returns, the execution environment of a is removed from the stack, leaving only the global execution environment) and then the scope chain of function B is created and initialized to the object contained in the scope of function B, which contains the scope chain of a. Finally, the active object of function B is created AO, and the parameter Z of B, the arguments object, and the This object are the properties of the AO. At this point the Ecstack will become this:

Ecstack = [//Execution Environment StackEC (B) = {//Create the execution environment for B and at the top of the scope chain[Scope]:ao (A),//scope chain to function A,AO (a)->vo (G)         varAO (B) = {//Create the active object for function BZ:1, arguments:[], This: Window} scopechain:<ao (B),b[[scope]]>//list is initialized to B[[scope]], then AO (b) is added to the list header, at which point the scope chain of B: AO (b)->ao (A)-vo (G) }, EC (A),//A's execution environment has been removed from the top of the stack,EC (G) = {//Global Execution Environmentvo:{//defining global variable Objects...//contains the original properties of the global objectx = 1;//define variable xA =function(){...};//define function AA[[scope]] = This;//definition A of scope,a[[scope]] = = VO (G)         }    }];

When function B executes "x+y+z", the X, Y, and z three identifiers need to be parsed one by one, and the parsing process follows the variable lookup rule: finds the attribute in its active object first, stops the lookup and returns if it exists, and, if it does not, continues to find it from the top of its scope chain until it is found Returns "Undefined" if the variable is not found on the entire scope chain. From the above analysis, we can see that the scope chain of function B is this:

AO (B)->ao (A)->vo (G)

Therefore, the variable x is found in AO (a), not the X in Vo (G), the variable y is also found in AO (a), and the variable z is found in its own AO (B). So the result of execution: 2+1+1=4.

A simple summary of the language

After understanding the working mechanism of JS engine, we can not only stay at the level of understanding the concept, but as a basic tool to optimize and improve our actual work of the code, improve the efficiency of implementation, the actual value is our real purpose. In terms of the variable lookup mechanism, if your code is deeply nested, each time a global variable is referenced, the JS engine looks for the entire scope chain, such as the bottom window and document object at the scope chain, so we can do a lot of performance optimization around this problem. Of course, there are other aspects of the optimization, not to repeat here, this article only as a point!

by @ One pixel 2015

JavaScript from definition to execution, those things you should know

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.