Home > Article > Web Front-end > Understand the execution context, execution stack, and event loop in JS
This article takes you through the execution context, execution stack, and event loop in Javascript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
The following concepts, whether they are execution context
or execution stack
, are very abstract in the specification. , the understanding of many contents actually relies on imagination. If there are any mistakes, please correct me.
Execution Context
In short, execution context (Execution Context) is an abstraction of the environment in which the executable code is running. Used to trace the evaluation of variables in a block of code. This is a concept that I have summarized. It may be somewhat inaccurate. You can also refer to the real standard definition.
But in general, there are three key points:
Only executable code will have an execution context
Execution contexts are stateful: running state (Perform), suspend state (Suspend), and resume (Resume). The execution context in the Perfrom state is called the running execution context (Running Execution Context)
Execution context is not equivalent to the lexical environment at all, and the relationship is hard to say. It's just that the former quoted the latter.
When executing a JS script, there can be multiple execution contexts, but there is only one runtime context (the same is true for asynchronous, As for why four are mentioned...three Isn’t it common knowledge that there are four great kings...).
And ES specification stipulates that the executable codes are as follows:
Global code
Function code
Eval statement
Module code
In other words, look at the following code:
var g=111 function f(){ console.log(g); for(let i =0; i <p> If the above code is run, only two execution contexts will be generated: </p>
global
Functionf
(*), then there will be only one execution context in the end, because function
f will not be executed at all, and naturally there will be no corresponding execution context. The only confusing thing in it is that it is
for-loop, but
it is not executable code at all, so it is part of the function execution context.
Important components of execution context
An execution context can be abstracted as:ExecutionContext = { State: LexEnv = { This: , OuterEnv: , DecRec:{ //... identifiername-variable } } VaEnv = { This: , OuterEnv: , VarRec:{ //... identifiername-variable } } }In fact, there are two in an execution context Very important components:
LexicalEnvironmentComponent (lexical environment component) and
VariableEnvironmentComponent (variable environment component). The lexical environment component points to the
lexical environment (LexEnv) in current code, and the variable environment component points to the
variable environment of current code (VarEnv).
execution context, one very important part is the scope chain, but in execution context## No relevant content was seen in #. However, the scope chain does exist. It is in the [[Scope]] internal property and can be seen directly through the browser
. But it can also be understood this way. When an execution context is created, not only the
of the current lexical environment will be created, but also LexEnv.OutEnv
, ## will be created. #LexEnv.OutEnv.OutEnv… until it extends to the whole world.
Creation and destruction of execution context
1. Create a new execution context (ExecutionContext, EC)
2. Create the current lexical environment (LexEnv and VarEnv) 3. Point theLexicalEnvironmentComponent
andVariableEnvironmentComponent of the execution context to the
LexEnv and
VarEnv## in the current environment. #middle. 4. Push the new execution context into the
execution stack
and become the
. 5. Instantiate and initialize the identifiers within the executable code block:
Collect all declared identifiers in the current lexical environment
#Intovar are included in the VarNames collection. At this stage, identifier names will be processed Detection, if the identifier declared with
let/const/... is the same as the identifier in
VarNames, an error will be reported. Instantiate the identifier in
DecRec
VarNames are bound to
ObjRec and are directly initialized to
undefined after instantiation.
对于function
声明的函数,将直接指向函数对象,并也会绑定到ObjRec中,这是浏览器默认行为。
6、运行代码。
非var声明的标识符会在声明处进行初始化(默认为undefined
)。
完成所有变量的赋值,并可能会一直在变化。
7、运行完毕从 执行栈
中弹出。
备注:
This
绑定,大部分情况可以用过去的说法解释,然而某些情况下却不尽然。执行栈与事件循环
执行栈(Execution Stack)就是由执行上下文构成的堆栈,类似于Call Stack
。
1、当Javascript引擎
遇到一段可执行代码时,新建一个执行上下文。
2、将它推入执行栈中。并设置为运行时执行上下文。
3、执行上下文运行完毕,弹出销毁恢复并将原执行上下文设为运行时。
总觉得这些没什么好说的,但是水一下吧
执行栈最重要的部分并非是执行栈概念本身,而是与任务队列的关系,它是事件循环的入门关键概念之一。
众所周知,Javascript语言是单线程的,此处的执行栈就相当于主线程的调用栈,也是唯一一个调用栈,至于什么是主线程可以查阅相关资料,这里有些超纲了……
那么javascript是如何实现异步的?
确切来说,这不是Javascript核心的部分,它是结合浏览器API(如Web Worker, Browser-context了解一下)实现的。
在事件循环中(事件处理过程),有两个极其重要的概念:
这两个概念,是抽象滴。
在Javascript中,一个任务也可以称之为事件,通常是一个函数回调,由许多任务组成的队列,就是所谓的任务序列了。任务序列有很多分类,例如:作业序列(Job Quenue)、消息序列(Message Quenue),本质没区别。
不必再深入了解,现在需要记住的是:一个任务序列中的任务如果想要被执行,就必须将它取出放入执行栈中。
例如下面的代码:
var temp = 10; console.log('push task1'); setTimeout(function task1(){ temp+=10; console.log(temp+'task1 okay! '); },1000) console.log('taskquenue=[task1]; push task2'); setTimeout(function task2(){ temp*=10; console.log(temp+'task2 okay! '); },500) console.log('taskquenue=[task1,task2]; push task3'); setTimeout(function task3(){ temp*= -0.2; console.log(temp+'task3 okay! '); },1500) console.log('taskquenue=[task1, task2,task3]');
输出如下:
push task1 taskquenue=[task1]; push task2 taskquenue=[task1,task2]; push task3 taskquenue=[task1, task2,task3] 100task2 okay! 110task1 okay! -22task3 okay!
setTimeout
是一个定时器,它能够将任务放到任务队列中。如图:
task1
:task2
:task3
:执行到此处, task1
、task2
和task3
都被放入了任务队列; 然后执行栈全部执行完毕后,开始处理任务队列中的任务。
为什么任务队列中的任务必须在执行栈空时后执行呢?
C
and Java
or look at the content of the operating system. Now start processing the task:
task2
:task1
:task3
:Okay, an event loopThat’s it.
ThenJavascript engineenters the sleep phase(Javascript engine never ends!), waits for new tasks to be executed, and then starts the next event loop.
This is my Intensive Reading Javascript SeriesThe third article, I was caught off guardEvent Loop, it seems It goes into a lot of depth at once... But I think this is the most unreasonable programming arrangement. Most documents separate task sequence and call stack , but in ~~_____~~, they should be one, and they should not be separated for any convenient reason.
In-depth Javascript, in addition to reading the specifications, it is best to also read the implementation documents of the JS engine. Some advanced content is not in the specifications, but in these documents (please search it on Google , it can also be searched on Baidu).
If you are interested in Javascript engine, you can refer to:
Although, it is extremely not recommended for novices to look at the V8 source code all at once. The feeling of having a splitting headache and shaking all over is really enjoyable. …… Recommended related tutorials:
JavaScript video tutorialThe above is the detailed content of Understand the execution context, execution stack, and event loop in JS. For more information, please follow other related articles on the PHP Chinese website!