


From definition to execution of JavaScript, 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 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.
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, the execution result is 4, we will divide it below Global initialization, Execute function A, Execute function B Three 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). There is only one copy of this object globally. A property is accessible from anywhere and exists throughout the application's lifetime. 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). 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) associated with EC Object) VO, and point VO to the global object. VO not only contains the original properties of the global object, but also includes the globally defined variable x and function A. At the same time, when defining function A, it also adds Create an internal attribute scope and point 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 where function B is defined. The environment where 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) } } ];
3. Execute function B
After function A is executed, a reference to B is returned , and assigned to variable C. Executing C(1) is equivalent to executing B(1). The JS engine needs to complete the following work:
首先,还和上面一样,创建函数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对象就存在这个问题,因此我们围绕这个问题可以做很多性能优化的工作,当然还有其他方面的优化,此处不再赘述,本文仅当作抛砖引玉吧!
The above is the detailed content of Detailed introduction to JavaScript from definition to execution, what all programmers should know. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
