Hello everyone ~, I am little deer, the public account: “little deer animation learning programming” original author.
The second issue of 2021.
You must be very confused by the title of this issue, why simple but not simple, simple but not simple implementation context? So let me just explain that some abstract concepts in javaScript, we can make them very complicated, we can make them very simple, we can make them both complicated and simple.
Well, I recently reviewed these abstract concepts and found that some concepts could not be well integrated before, so I wrote these relatively abstract and difficult concepts as several articles.
A Google search for “execution context” will bring up a few good articles that are relatively high on the list.
-
Understand the execution context and execution stack in JavaScript
-
In-depth understanding of JavaScript execution context and execution stack
-
JavaScript deep into the execution context
After reading these articles, the author tries his best to explain these abstract concepts with many words and relatively few pictures. I personally feel that in order to better understand abstract concepts, we have to use visual images to reduce the understanding and misunderstanding between the writer and the reader. So, don’t worry, this article will explain these abstract concepts in a simple way by adding more pictures.
This article has been included in the second issue of Github blog, welcome everyone ~ Star, if there are problems or issues in this article, welcome to leave a message below or Github!
The current directory
-
1. Execution context
-
1.1 JavaScript engine
-
1.2 execution stack
-
1.3 Execution Context
-
-
2. Classification of execution context
-
2.1 Global execution context
-
2.2 Local execution context
-
-
3. Execute two phases of context
-
3.1 Creation Phase
-
3.2 Execution Phase
-
-
4, summary
1. Execution context
1.1 JavaScript engine
When it comes to execution context, we have to start with JavaScript engines. What is a JavaScript engine? Consider that this article is not specifically about JavaScript engines, so Google it yourself. To put it bluntly, JavaScript engines are designed to “interpret”, “compile”, and “execute” JavaScript code. After all, JavaScript code written by developers can only be recognized by developers and handed to computers. So it takes a lot of interpretation and translation to make sense of this JavaScript code.
1.2 Execution Stack
Note: Ensure that the JavaScript code is executed “sequentially”.
JavaScript engine can execute JS code, so in what order to execute, and how to ensure that the order is not disrupted. Let’s start with some simple code:
var foo2 = function () {
console.log('foo2');
}
var foo1 = function () {
console.log('foo1');
foo2()
console.log('foo3')
}
foo1(); Foo1 foo2 foo3
Copy the code
By executing the code snippet above, the output order is ‘foo1 foo2 foo3’.
Code execution, foo1() function to execute first, first output ‘foo1’, encountered foo2() function to execute the command, give the execution authority to foo2, foo2 function body to execute, output ‘foo2’. When foo2 is finished, hand the execution back to foo1 and print ‘foo3’.
We can find the above code execution pattern, the first function to be executed, at the end of the exit, the last function to be executed, the first to complete. This execution order is not “stack” of “first in, last out” “last in, first out” structure. JavaScript engines refer to this execution structure as an “execution stack” to ensure the sequence of JavaScript code.
1.3 Execution Context
Note: Modularize the code you execute — categorize the execution context.
What is an execution context? Although it is difficult for us to understand the meaning of “execution context” directly, it is easy to understand what it represents. I will concretize the abstract concept of “execution context” below.
We have explained above that the JavaScript engine uses the execution stack to ensure the execution order of the code, but the execution process needs to involve some complicated situations such as scope definition (scope) of variables, closures and so on. We need the JavaScript engine to introduce a mechanism to solve these seemingly complicated problems. So the concept of “execution context” was born.
But what is the execution context? This has to remind me of modular development of components, before a web application code from the top to the next file written down thousands of lines of code, difficult to read, difficult to maintain, so there is the modular development later. Each module has its own functionality, with its own local variables and styles.
In order to better interpret and execute code, JavaScript engines introduce concepts such as “execution context” for component modules to manage the complexity of runtime code.
2. Classification of execution context
The concrete concept of an abstract “execution context” similar to a “module” is easy to understand. Of course, the execution context is also called “module” has different classification, here specifically expand two types, “global execution context” and “local execution context”.
2.1 Global Execution Context
This “module” consists of two parts, “global object” and “this”.
The following diagram shows the global execution context in its most basic form. Contains a window object and a this variable that refers to the window object, as shown in the printout at the far right.
From this we can see that the execution context can be understood as a module (or fragment) of an in-memory collection of objects and variables, which is why it can be thought of as similar to a module (among other things).
Note: for easy understanding, the definition is my own summary, if there is a lack of welcome to point out ~
2.2 Local execution context
The local execution context is similar to, but not identical to, the global execution context. In the context of local execution of functions, there are two things to note:
-
The parameters passed to the function are stored as variables in the local execution context
-
The local context has a arguments object (reference)
The local execution context is covered in detail in the next two phases.
3. Execute two phases of context
Both global and local execution contexts go through two phases, “create” and “execute.”
Here we have a code:
var name = "The deer";
var age = 23;
function getInfo(){
return {
name: name,
age: age
};
}
Copy the code
3.1 Creation Phase
The creation phase does the following:
- Create global objects in heap memory (
global object
) — the browser environment iswindows
.Node
The environment isGlobal
- let
this
The variable points to this global object - Sets the memory space for variables and functions in the current execution context
- Add the declared variable to memory (while hanging on the global object) and assign a value to the variable
undifined
The function stores strings
Note: Left (1) the code executed, left (2) the state in execution context memory after the creation phase, right (1) the state of the global object during the creation phase.
Before executing the code, the JavaScript engine creates the global execution context in the heap, generates the global object, and points to this variable. JavaScript finds two variables declared in the code, name and age, allocates memory space in the global execution context, stores the variable in memory, assigns the variable a value of undefined, and stores the function as a string in memory.
Note: The process of specifying a default value (undefined) for a variable declaration during creation is called “variable promotion.”
3.2 Execution Stage
Once the global Execution context is created, the transition from Creation to Execution begins. The JavaScript engine starts running and executing the code line by line, assigning values to variables that were put into memory during the creation phase.
Note: The code executed in the left (1) diagram, the state in the execution context memory after the execution phase is completed in the left (2) diagram, and the state of the global object in the execution phase in the right (1) diagram.
Local and global execution contexts are created and executed exactly the same way. But the global execution context is created once, whereas the function local execution context is created with each call to the function.
Again, the result is as follows:
var name = "The deer";
var age = 23;
function getInfo(name){
console.log(name);
return {
name: name,
age: age
};
}
getInfo(name);
Copy the code
Function local context execution state is as follows:
Note: Since no new variables are defined in the function, there is no variable promotion here.
We know what is the function local context, when the function local context is finished, it will execute the stack operation, handing the execution authority to the parent execution context (may be local execution context, may be global execution context), the above getInfo function completed execution state is shown below.
When the function completes, the local execution context goes out of the stack and is destroyed, leaving execution to the global execution context to continue executing the rest of the code.
Since JavaScript is single-threaded, only one task can be executed at a time. For your convenience, the left (3) figure shows the execution stack invocation. Of course, we can also see that the left (2) figure simulates the operation of the execution stack in a nested manner, with each nested option representing a new execution context in the stack.
4, summary
Execution context is a very important concept in JavaScript, and the concepts of scope, scope, closure, this, and so on will be linked to this article in future installments of advanced articles. Try to understand these abstract concepts in principle.
As an aside, why all of a sudden start with the basics this year? I felt that although I had memorized some concepts during the self-study preparation for the interview, I failed to understand them thoroughly. Therefore, I planned to make clear these points that I had not understood thoroughly before through each article.
❤️ original is not easy, welcome quality three even [likes + favorites + comments]
The articles of each issue are sorted out from spare time outside work, involving some difficult concepts, I will consult a large number of materials and self-thinking, inevitably there will be some clerical errors and deficiencies, also welcome readers’ criticism. Original is not easy, if you feel good, I hope to like more support ~, we will see you next time ~
I am Xiaolu. This article is updated on Github simultaneously. You can also search “Xiaolu Animation Learning Programming” on wechat to receive the notification of article update in the first time, and reply “front-end” to get the preparation interview booklet prepared by Xiaolu.