Home>Article>Web Front-end> What you need to know about javascript from definition to execution
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 objects, execution environments, variable objects, active objects, scopes and scope chains, 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.
Related learning recommendations:javascript video tutorial
var x = 1; //定义一个全局变量 x function A(y){ var x = 2; //定义一个局部变量 x function B(z){ //定义一个内部函数 B console.log(x+y+z); } return B; //返回函数B的引用 } var C = A(1); //执行A,返回B C(1); //执行函数B
This demo is a closure, and the execution result is 4. We will divide it into ## below. #Global initialization,Execute function A,Execute function BThree stages to analyze the working mechanism of the JS engine:
1. Global initialization
When the JS engine enters a piece of executable code, it needs to complete the following three initialization tasks: First, create a global object (Global Object). This object only exists globally. Its properties are accessible from anywhere, and its existence accompanies the entire life cycle of the application. When the global object is created, commonly used JS objects such as Math, String, Date, and document are used as its properties. Since this global object cannot be accessed directly through the name, there is another attribute window, and the window is pointed to itself, so that the global object can be accessed through the 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). At the same time, it must 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 points VO to the global object, VO It 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 the scope is pointed to VO . When each function is defined, a scope attribute associated with it is created. 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, it The scope chain is initialized to 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 where function B is defined. The environment where function B is defined is A's active object AO, and 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://链表初始化为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) } } ];
3. Execute function B
After function A is executed, the reference of B is returned and assigned to the variable. C, executing C(1) is equivalent to executing B(1). The JS engine needs to complete the following work: First, as above, create the execution environment EC of function B, and then push the EC into the execution environment top of the stack and obtain 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 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, A's execution environment will be deleted from the stack, leaving only the global execution environment)然后,创建函数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://链表初始化为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对象就存在这个问题,因此我们围绕这个问题可以做很多性能优化的工作,当然还有其他方面的优化,此处不再赘述,本文仅 当作抛砖引玉吧!
The above is the detailed content of What you need to know about javascript from definition to execution. For more information, please follow other related articles on the PHP Chinese website!