当前位置:网站首页>Understand JS execution context in an article
Understand JS execution context in an article
2022-07-27 14:27:00 【Planetary flight】

one * lead
Execution context is a very important concept , By reading it , You will understand why there is so-called variable promotion , Why? let An error is reported when a variable declared but not assigned is used , but var nevertheless undefined, Put it all together , It will also deepen your understanding of this The understanding of the .
We all know ,JS The execution order of code is always different from that of code , When you put aside the asynchronous problem, you will find that even synchronous code , Its implementation is also inconsistent with your expectations , such as :
function f1() {
console.log(' Listening to the wind is the wind ');
};
f1(); //echo
function f1() {
console.log('echo');
};
f1(); //echo
In the order in which the code is written , It should be output first Listening to the wind is the wind , Then the output echo That's right , unfortunately , Both outputs are echo; If we change the function declaration in the above code to function expression , It turned out to be different :
var f1 = function () {
console.log(' Listening to the wind is the wind ');
};
f1(); // Listening to the wind is the wind
var f1 = function() {
console.log('echo');
};
f1(); //echo
This means that the code must have some subtle changes before execution ,JS What did the engine do ? I have to mention JS Execution context .
Ii. * JS Execution context
JS Code before execution ,JS The engine always has to do some preparation , This job is actually to create a corresponding execution context ;
There are only three types of execution contexts , Global execution context , Function context , And eval Context ; because eval Generally not used , No discussion here .
Ii. * one Global execution context
There is only one global execution context , In the client, it is usually created by the browser , That's what we know window object , We can get through this Access it directly .

Global object window A large number of methods and properties are predefined on , We can directly access these attribute methods anywhere in the global environment , meanwhile window The object is still var The vector of declared global variables . We go through var Global objects created , Both can pass window Direct access .

Ii. * Ii. Function execution context
Function execution context can be numerous , Whenever a function is called, a function context is created ; It should be noted that , The same function is called more than once , Will create a new context .
When it comes to that, do you think , Different kinds of context , And there are so many more created , What is the relationship between them , Who is going to manage these contexts , So we have to talk about the execution context stack .
3 * Execution context stack ( Execution stack )
Execution context stack ( Hereinafter referred to as the execution stack ) Also called call stack , The execution stack is used to store all contexts created during code execution , have LIFO(Last In First Out Last in, first out , That is, first in and then out ) Characteristics of .
JS Code runs for the first time , A global execution context is created and pushed into the execution stack , Then every time a function is called , Will create a new function execution context and push it into the stack ; Due to the execution stack LIFO Characteristics of , So it can be interpreted as ,JS There will always be a global execution context at the bottom of the execution stack before the code is executed .
function f1() {
f2();
console.log(1);
};
function f2() {
f3();
console.log(2);
};
function f3() {
console.log(3);
};
f1();//3 2 1
We explain the execution process of the above code through the relationship between the execution stack and the context , For ease of understanding , We pretend that the execution stack is an array , At the beginning of code execution, the global execution context must be created and pushed into the stack , So the process is roughly as follows :
// Create a global execution context before code execution
ECStack = [globalContext];
// f1 call
ECStack.push('f1 functionContext');
// f1 Call again f2,f2 Cannot... Until execution is complete console 1
ECStack.push('f2 functionContext');
// f2 Call again f3,f3 Cannot... Until execution is complete console 2
ECStack.push('f3 functionContext');
// f3 completion of enforcement , Output 3 And out of the stack
ECStack.pop();
// f2 completion of enforcement , Output 2 And out of the stack
ECStack.pop();
// f1 completion of enforcement , Output 1 And out of the stack
ECStack.pop();
// There is only one global execution context left in the execution stack
So over here , We explained the storage rules of execution stack and execution context ; Remember before I mentioned code execution JS Is the engine ready to create an execution context , How to create it , We went on to say .
boss * Execution context creation phase
Execution context creation is divided into Create a stage And Execution phase Two phases , The more difficult to understand is the creation phase , Let's start with the creation phase .
JS The creation phase of execution context is mainly responsible for three things : determine this— Create lexical environment components (LexicalEnvironment)— Create variable environment components (VariableEnvironment)
Here I directly draw on the pseudocode of other people's translation materials , To represent the creation process :
ExecutionContext = {
// determine this Value
ThisBinding = <this value>,
// Create lexical environment components
LexicalEnvironment = {
},
// Create variable environment components
VariableEnvironment = {
},
};
If you have read other articles about execution context, there must be some questions , The execution context creation process should not explain this, Scope and variable object / Is the object of the activity right , How can it be different from what other places say , I'll explain that later .
boss * one determine this
The official name is This Binding, In the context of global execution ,this Always point to global objects , For example, in browser environment this Point to window object .
In the context of function execution ,this The value of depends on how the function is called , If called by an object , that this Point to this object . otherwise this Generally points to global objects window perhaps undefined( Strict mode ).
I wrote a special introduction before this 's blog post , Now it seems that the writing is very bad , After that, I will understand and write an easy to understand article .
boss * Ii. Lexical environment component
A lexical environment is a structure that contains a mapping of identifier variables , The identifier here represents the variable / Name of function , Variables are for real objects 【 Includes function type objects 】 Or a reference to the original value .
Lexical environment consists of environmental record and external environment introduction record .
Environment records are used to store the actual positions of variables and function declarations in the current environment ; It's easy to understand the external environment , It is used to save other external environments that can be accessed by its own environment , So when it comes to this , Is it a little scope chain ?
We mentioned the global execution context and the function execution context earlier , Therefore, the lexical environment is divided into global lexical environment and functional lexical environment .
Global lexical environment component :
The introduction of the external environment is recorded as null, Because it's the outermost environment , In addition, it records all the properties in the current environment 、 Method location .
Lexical environment component :
Contains all attributes and methods defined by the user in the function , It also includes a arguments object . The introduction of external environment of functional lexical environment can be global environment , It can also be other function environments , This is based on the actual code .
The pseudocode in the translation is borrowed here ( The environment record is also different in the global and function , Global environment record is called object environment record , The environment record in the function calls the explicit environment record , I'm confused , There is a display below ):
// Global environment
GlobalExectionContext = {
// Global Lexical Environment
LexicalEnvironment: {
// Environmental records
EnvironmentRecord: {
Type: "Object", // Type is object environment record
// The identifier is bound here
},
outer: < null >// External environment reference is null
}
};
// Function of the environment
FunctionExectionContext = {
// Functional Lexical Environment
LexicalEnvironment: {
// Environmental records
EnvironmentRecord: {
Type: "Declarative", // The type is declarative environmental record
// The identifier is bound here
},
outer: < Global or outerfunction environment reference >
}
};
boss * 3 Variable environment component
Variable environment is also lexical environment , It has all the attributes of lexical environment , There are also environmental records and external environment introduction . stay ES6 The only difference is that the lexical environment is used to store function declarations and let const Declared variables , And the variable environment just stores var Declared variables .
We understand them through a string of pseudocodes :
let a = 20;
const b = 30;
var c;
function multiply(e, f) {
var g = 20;
return e * f * g;
}
c = multiply(20, 30);
We use pseudo code to describe the creation process of execution context in the above code :
// Global execution context
GlobalExectionContext = {
// this Bind as global object
ThisBinding: <Global Object>,
// Lexical environment
LexicalEnvironment: {
// Environmental records
EnvironmentRecord: {
Type: "Object", // Object environment record
// The identifier is bound here let const Variables created a b Here
a: < uninitialized >,
b: < uninitialized >,
multiply: < func >
}
// The external environment of global environment is introduced as null
outer: <null>
},
VariableEnvironment: {
EnvironmentRecord: {
Type: "Object", // Object environment record
// The identifier is bound here var Created c Here
c: undefined,
}
// The external environment of global environment is introduced as null
outer: <null>
}
}
// Function execution context
FunctionExectionContext = {
// Because the function is called by default this Binding is also a global object
ThisBinding: <Global Object>,
// Lexical environment
LexicalEnvironment: {
EnvironmentRecord: {
Type: "Declarative", // Declarative environmental records
// The identifier is bound here arguments The object is here
Arguments: {
0: 20, 1: 30, length: 2},
},
// The introduction of the external environment is recorded as </Global>
outer: <GlobalEnvironment>
},
VariableEnvironment: {
EnvironmentRecord: {
Type: "Declarative", // Declarative environmental records
// The identifier is bound here var Created g Here
g: undefined
},
// The introduction of the external environment is recorded as </Global>
outer: <GlobalEnvironment>
}
}
I don't know if you noticed , In the execution context creation phase , Function declaration and var The declared variable has been given a value during the creation phase ,var The declaration is set to undefined, The function is set as its own function , and let const Set to uninitialized [ˌʌnɪˈnɪʃəˌlaɪzd] uninitialized .
Now you always know what's going on with variable promotion and function declaration in advance , And why let const Why is there a temporary death zone , This is because the scope creation phase JS The engine assigns different initialization values to both .
In addition to the context creation phase , And the implementation phase , This should be well understood , When the code is executed, the value is assigned according to the previous environment record , For example, in the early days var In the creation phase, for undefined, If there is a value, it is assigned , image let const The value is uninitialized , If there is a value, assign it , No value gives undefined.
wu * About variable objects and active objects
Answer the questions above , Why other people's blog introduction context is about scope , Variable objects and active objects , I have become a lexical environment , Variable environment .
I also have this question in reading related materials , What can be ascertained from a review is , The concept of variable object and active object is ES3 Put forward the old concept , from ES5 I began to use lexical environment and variable environment instead of , Because better explanation .
In the above , We explain why by introducing lexical environment and variable environment var There will be variable Promotion , Why? let const No, , It is difficult to explain through variable object and active object , It is in JavaScript In the process of updating, we are constantly making up for the original design hole .
secondly , The concepts of Lexical Environment and variable object can also be corresponded .
We know that both variable objects and active objects are variable objects , Variable objects are data scopes related to the execution context , Stored variables and function declarations defined in context . And in the context of functions , We use moving objects (activation object, AO) To represent a variable object .
So this doesn't exactly correspond to the global lexical record and the functional lexical record . And because of ES6 Newly added let const No variable promotion , So we have the concept of Lexical Environment and variable environment to explain this problem .
So when it comes to this , You don't have to do it for the lexical environment , The concept of variable object conflicts .
Let's summarize the concepts mentioned above .
lu * total
1. The global execution context is generally created by the browser , When the code executes, it creates ; Function execution context is created only when the function is called , How many times a function is called, how many contexts will be created .
2. The call stack is used to hold all execution contexts , Satisfy FILO The rules .
3. The execution context creation phase is divided into binding this, Create a lexical environment , Variable environment three steps , The difference between the two is that the lexical environment stores function declarations and const let Declared variables , The variable environment only stores var Declared variables .
4. Lexical environment consists of two parts: environment record and external environment introduction record , The global context is not the same as the external environment of the function context , Global is null, Functions are global or other function environments . Environmental records are not the same , Global call object environment record , Function is called declarative environment record .
5. You should understand why there is variable Promotion , Function enhancement , and let const No, .
6.ES3 The previous concepts of variable object and active object are in ES5 Then by Lexical Environment , Variable environment to explain , There is no conflict between the two concepts , The latter is easier to understand .
Finally, a mind map of the knowledge points in this article is attached :

I have to say that I am tired of reading relevant articles , I also hope it can help you , So over here , In this paper, the end .
边栏推荐
- [training day4] sequence transformation [thinking]
- 平板模切机
- arduino+ZE08-CH2O甲醛模块,输出甲醛含量
- PROFINET simulator tutorial
- 西测测试深交所上市:年营收2.4亿募资9亿 市值47亿
- 面向流行性疾病科普的用户问题理解与答案内容组织
- HDU1422 重温世界杯【DP】
- Slam overview Reading Note 6: slam research based on image semantics: application-oriented solutions for autonomous navigation of mobile robots 2020
- Why does script file 'd:\anaconda3\envs\pad appear_ env\Scripts\pip-script. py‘ is not present.
- [luogu_p4556] [Vani has an appointment] tail in rainy days / [template] segment tree merging
猜你喜欢

线程知识总结

汉字风格迁移篇---对抗性区分域适应(L1)Adversarial Discriminative Domain Adaptation

PROFINET simulator tutorial

West test Shenzhen Stock Exchange listing: annual revenue of 240million, fund-raising of 900million, market value of 4.7 billion

JS什么是声明提前?函数与变量声明提前的先后顺序(执行上下文铺垫篇)

Schematic diagram of C measuring tool
![[idea] set to extract serialVersionUID](/img/ef/7eee4639cd4306a2a7a53d73528bbd.png)
[idea] set to extract serialVersionUID

【论文精读】Grounded Language-Image Pre-training(GLIP)

JS 疫情宅在家,学习不能停,七千字长文助你彻底弄懂原型与原型链

Utnet hybrid transformer for medical image segmentation
随机推荐
Vscode -- create template file
力扣SQL语句习题,错题记录
Some key information about Max animation (shift+v)
Positive mask, negative mask, wildcard
【论文精读】Grounded Language-Image Pre-training(GLIP)
Advanced MySQL III. storage engine
log4j2 jdbc appender
watch VS watchEffect
LeetCode·每日一题·592.分数加减运算·模拟
PROFINET simulator tutorial
Is the security of online brokerage app account opening guaranteed?
Document translation__ Tvreg V2: variational imaging method for denoising, deconvolution, repair and segmentation (part)
A Keypoint-based Global Association Network for Lane Detection
用命令如何返回上级目录
YOLOX改进之一:添加CBAM、SE、ECA注意力机制
微策生物IPO过会:年营收12.6亿 睿泓投资与耀合医药是股东
STM32——电容触摸按键实验
GoPro access - control and preview GoPro according to GoPro official document /demo
网上券商APP开户安全有保障吗?
Slam overview Reading Note 4: a survey on deep learning for localization and mapping: towards the age of spatial 2020