javascript From definition to execution, the JS engine does a lot of initialization work at the implementation layer. Therefore, before learning the working mechanism of the JS engine, we need to introduce several related concepts: execution environment stack, global object, execution environment, variable object , active objects, scope and scope chain, etc. These concepts are the core components of the JS engine. The purpose of this article is not to explain each concept to you in isolation, but to use a simple demo to conduct analysis and comprehensively explain every detail of the JS engine from definition to execution, as well as the role these concepts play in it.
var x = 1; //定义一个全局变量 xfunction A(y){ var x = 2; //定义一个局部变量 x function B(z){ //定义一个内部函数 B console.log(x+y+z); } return B; //返回函数B的引用}var C = A(1); //执行A,返回BC(1); //执行函数B
This demo is a closure, the execution result is 4, below we will divide global initialization, execution function A, Execute function B Three stages to analyze the working mechanism of the JS engine:
1. Global initialization
When the JS engine enters an executable code, The following three initialization tasks need to be completed:
First, create a global object (Global Object). There is only one copy of this object globally. Its properties can be accessed anywhere, and its existence is accompanied by the application. the entire life cycle. When the global object is created, commonly used JS objects such as Math, String, Date, and document are used as its attributes. Since this global object cannot be accessed directly by name, there is another attribute window, and window is pointed to itself, so that the global object can be accessed through window. The general structure of the global object simulated with pseudo code is as follows:
//创建一个全局对象var globalObject = { Math:{}, String:{}, Date:{}, document:{}, //DOM操作 ... window:this //让window属性指向了自身}
Then, the JS engine needs to build an execution environment stack (Execution Context Stack), and at the same time, also create a global execution Environment (Execution Context) EC, and push this global execution environment EC into the execution environment stack. The function of the execution environment stack is to ensure that the program can be executed in the correct order. In JavaScript, each function has its own execution environment. When a function is executed, the execution environment of the function will be pushed to the top of the execution environment stack and obtain execution rights. When the function completes execution, its execution environment is removed from the top of the stack and the execution rights are returned to the previous execution environment. We use pseudo code to simulate the relationship between the execution environment stack and EC:
var ECStack = []; //定义一个执行环境栈,类似于数组var EC = {}; //创建一个执行空间,//ECMA-262规范并没有对EC的数据结构做明确的定义,你可以理解为在内存中分配的一块空间ECStack.push(EC); //进入函数,压入执行环境ECStack.pop(EC); //函数返回后,删除执行环境
Finally, the JS engine also creates a global variable object (Varibale Object) VO associated with EC, and puts VO points to the global object. VO not only contains the original attributes of the global object, but also includes the globally defined variable x and function A. At the same time, when defining function A, an internal attribute scope is also added to A. And pointed the scope to VO. When each function is defined, a scope attribute is created associated with it. The scope always points to the environment in which the function is defined. The ECStack structure at this time is as follows:
ECStack = [ //执行环境栈 EC(G) = { //全局执行环境 VO(G):{ //定义全局变量对象 ... //包含全局对象原有的属性 x = 1; //定义变量x A = function(){...}; //定义函数A A[[scope]] = this; //定义A的scope,并赋值为VO本身 } } ];
2. Execution function A
When execution enters A(1), the JS engine needs to complete the following Work:
First, the JS engine will create the execution environment EC of function A, and then the EC is pushed to the top of the execution environment stack and obtains execution rights. At this time, there are two execution environments in the execution environment stack, namely the global execution environment and the execution environment of function A. 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 (Scope Chain) of function A. In JavaScript, each execution environment has its own scope chain for identifier resolution. When the execution environment is created, its scope chain is initialized. It is the object contained in the scope of the currently running function.
Then, the JS engine will create an Activation Object (Activation Object) AO of the current function. The activity object here plays the role of a variable object, but its name is different in the function (you can think of the variable object is a general concept, and the active object is a branch of it), AO contains the formal parameters of the function, the arguments object, this object, and the definition of local variables and internal functions, and then the AO will be pushed into the scope chain top. It should be noted that when defining function B, the JS engine will also add a scope attribute to B and point the scope to the environment in which function B is defined. The environment in which function B is defined is the active object AO of A. AO is located at the front end of the linked list. Since the linked list is connected end to end, the scope of function B points to the entire scope chain of A. Let’s take a look at the ECStack structure at this time:
ECStack = [ //执行环境栈 EC(A) = { //A的执行环境 [scope]:VO(G), //VO是全局变量对象 AO(A) : { //创建函数A的活动对象 y:1, x:2, //定义局部变量x B:function(){...}, //定义函数B B[[scope]] = this; //this指代AO本身,而AO位于scopeChain的顶端,因此B[[scope]]指向整个作用域链 arguments:[],//平时我们在函数中访问的arguments就是AO中的arguments this:window //函数中的this指向调用者window对象 }, scopeChain:<AO(A),A[[scope]]> //链表初始化为A[[scope]],然后再把AO加入该作用域链的顶端,此时A的作用域链:AO(A)->VO(G) }, EC(G) = { //全局执行环境 VO(G):{ //创建全局变量对象 ... //包含全局对象原有的属性 x = 1; //定义变量x A = function(){...}; //定义函数A A[[scope]] = this; //定义A的scope,A[[scope]] == VO(G) } } ];
三、 执行函数B
函数A被执行以后,返回了B的引用,并赋值给了变量C,执行 C(1) 就相当于执行B(1),JS引擎需要完成以下工作:
首先,还和上面一样,创建函数B的执行环境EC,然后EC推入执行环境栈的顶部并获取执行权。 此时执行环境栈中有两个执行环境,分别是全局执行环境和函数B的执行环境,B的执行环境在栈顶,全局执行环境在栈的底部。(注意:当函数A返回后,A的执行环境就会从栈中被删除,只留下全局执行环境)然后,创建函数B的作用域链,并初始化为函数B的scope所包含的对象,即包含了A的作用域链。最后,创建函数B的活动对象AO,并将B的形参z, arguments对象 和 this对象作为AO的属性。此时ECStack将会变成这样:ECStack = [ //执行环境栈
EC(B) = { //创建B的执行环境,并处于作用域链的顶端 [scope]:AO(A), //指向函数A的作用域链,AO(A)->VO(G) var AO(B) = { //创建函数B的活动对象 z:1, arguments:[], this:window } scopeChain:<AO(B),B[[scope]]> //链表初始化为B[[scope]],再将AO(B)加入链表表头,此时B的作用域链:AO(B)->AO(A)-VO(G) }, EC(A), //A的执行环境已经从栈顶被删除, EC(G) = { //全局执行环境 VO:{ //定义全局变量对象 ... //包含全局对象原有的属性 x = 1; //定义变量x A = function(){...}; //定义函数A A[[scope]] = this; //定义A的scope,A[[scope]] == VO(G) } } ];
当函数B执行“x+y+z”时,需要对x、y、z 三个标识符进行一一解析,解析过程遵守变量查找规则:先查找自己的活动对象中是否存在该属性,如果存在,则停止查找并返回;如果不存在,继续沿着其作用域链从顶端依次查找,直到找到为止,如果整个作用域链上都未找到该变量,则返回“undefined”。从上面的分析可以看出函数B的作用域链是这样的:
AO(B)->AO(A)->VO(G)
因此,变量x会在AO(A)中被找到,而不会查找VO(G)中的x,变量y也会在AO(A)中被找到,变量z 在自身的AO(B)中就找到了。所以执行结果:2+1+1=4.
简单的总结语
了解了JS引擎的工作机制之后,我们不能只停留在理解概念的层面,而要将其作为基础工具,用以优化和改善我们在实际工作中的代码,提高执行效率,产生实际价值才是我们的真正目的。就拿变量查找机制来说,如果你的代码嵌套很深,每引用一次全局变量,JS引擎就要查找整个作用域链,比如处于作用域链的最底端window和document对象就存在这个问题,因此我们围绕这个问题可以做很多性能优化的工作,当然还有其他方面的优化,此处不再赘述,本文仅当作抛砖引玉吧!