Detailed explanation of execution context and call stack in JavaScript

Detailed explanation of execution context and call stack in JavaScript

1. What is the execution context

The code runs in a certain environment, which we call the execution environment, or execution context. According to different execution environments, we can divide them into three categories:

Global execution environment: the default environment when the code is first executed

Function execution environment: Whenever the execution flow enters a function body

Eval execution environment: When the text inside the eval function is executed

2. What is the Execution Context Stack?

Since it is a 'stack', it must conform to the characteristics of a 'stack', that is, the data structure is first-in, last-out. Let's look at a piece of code:

function cat(a){
    if(a<0){
        return false;
    }
    console.log('Push to stack:'+a);
    cat(a-1);
    console.log('Pop out:'+a);
}
cat(3);
// Push to stack: 3
// Push to stack: 2
// Push to stack: 1
// Push to stack: 0
// Pop stack: 0
// Pop: 1
// Pop: 2
// Pop: 3

Let's analyze the execution process of the above code:

① When the browser is loaded, the program enters the global execution context and pushes it into a stack (the first one to enter, so the bottom layer); there is only one function cat under this execution context, cat call, parameter 3;

② The program enters the cat function, that is, enters the execution context of the function, and pushes it into the stack (the second one to enter, so the second to last layer). Because the parameter 3 is greater than 0, it continues to execute and outputs 'Push stack: 3';

③The program continues to execute, calling the function cat, entering a new function execution context again, and continuing to push into the stack (the third entry, the third to last layer), with the parameter a-1, and looping step ②; here, it should be noted that because the function cat(a-1) is called, the next line of code 'Pop: a' (at this time a is still 3), that is, 'Pop: 3' is temporarily stranded and exists in the second to last layer of the stack.

④ Repeat steps ②③ and output 'Push: 2', 'Push: 1', 'Push: 0' in turn; at the same time, the outputs that are stranded are 'Pop: 2' (the third layer from the bottom of the stack), 'Pop: 1 (the fourth layer from the bottom of the stack)', and 'Pop: 0 (the fifth layer from the bottom of the stack)';

⑤ According to the characteristics of the stack, the four output items that are stranded are output in order: 'Push to stack: 3', 'Push to stack: 2', 'Push to stack: 1', 'Push to stack: 0';
The above is the specific situation of the execution context stack. Please practice the code manually, I believe it will be easy to understand thoroughly.

3. Details of the execution context stack process

We already know that each time a function is called, a new context is executed. Each execution context is divided into two phases: creation phase and execution phase. Creation phase: refers to the phase when the program calls a function but the code is not executed;
Execution phase: refers to the code execution phase such as variable allocation and function execution;

1. Creation phase

When the function is called at this stage, an execution context object (executionContextObj) is created, which contains three objects: scope chain object (scopeChain), variable object (variableObject, referred to as VO), and this object. VO includes variable declaration (variable), function declaration (function), parameters (arguments), etc.
These three objects are created in three steps:
Step 1: Initialize the scope chain (scopeChain) and allocate stack memory

Step 2: Create parameters, functions, and variables

Step 3: Determine the value of the context's 'this'

Let's further analyze the above steps with the code:

function cat(name) {
    var a = 'Year after year';
    var b = function () {};
    this.name = name;
    function c() {
        console.log(this.name);
    }
    c();
}
cat('There is fish');

When this code calls the function cat('有鱼'), the execution context is in the creation phase, and the code is parsed as follows:

cat execution context object = {
    scopeChain: { ... }, // 1. Create a scope chain and allocate stack memory variableObject: { 2. Create variable object arguments: { // 2.1 Parse parameter 0: 'There is fish',
            length: 1
        },
        name: '有鱼', // 2.1 Parse parameters, create parameter names, and assign parameters c: function c() // 2.2 Find function declaration c, and use c as an attribute and function c as a value a: undefined, // 2.3 Find variable declaration a, initialize it to undefined, only look at the declaration part at this stage, and do not assign a value b: undefined // 2.3 Find variable declaration b, initialize it to undefined, only look at the declaration part at this stage, and do not assign a value },
    this: { 3. Create this object this:cat('有鱼') // 3.1 Points to the object of this call name:undefined // 3.2 The object property name is initialized to undefined
    };
    c() //Enter the execution context of function c again, same as cat function, not expanded yet}

Through code analysis we can draw the following conclusions

① The order of the three steps cannot be messed up ② In the VO step, execute the function declaration first, then execute the variable declaration ③ Only parameters can be assigned at this stage, variables and functions can only be declared

2. Implementation

In this stage, the js interpreter executes the function code in the context, runs the js code line by line, and assigns values ​​to variables;
Or analyze it in combination with the code:

cat execution context object = {
    scopeChain: { ... },
    variableObject: { 
        arguments: { 
            0: 'There are fish',
            length: 1
        },
        name: 'There is fish', 
        c: function c(),
        a: '年年', // variable a is assigned a value b: function b // variable b is assigned a value },
    this: { 3. Create this object this:cat('There is fish') 
        name:'有鱼' // Assign a value to the object attribute name}
}

The above is a detailed explanation of the execution context and call stack in JavaScript. For more information about the execution context and call stack in JavaScript, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of JavaScript execution mechanism
  • Thoroughly understand the JavaScript execution mechanism
  • JS asynchronous execution principle and callback details
  • Execution context and execution stack example explanation in JavaScript
  • Detailed explanation of JavaScript execution model
  • In-depth explanation of Javascript execution context order
  • How to manually implement a JavaScript module executor
  • Javascript asynchronous process control serial execution detailed explanation
  • Use a few interview questions to look at the JavaScript execution mechanism

<<:  How to use Docker Compose to implement nginx load balancing

>>:  mysql query data for today, this week, this month, and last month

Recommend

The difference between mysql outer join and inner join query

The syntax for an outer join is as follows: SELEC...

WeChat applet date and time component (year, month, day, hour, and minute)

This article example shares the specific code of ...

How to implement on-demand import and global import in element-plus

Table of contents Import on demand: Global Import...

How to use type enhancement without typingscript

Preface Due to the weak typing of JS, loose writi...

JavaScript microtasks and macrotasks explained

Preface: js is a single-threaded language, so it ...

Node.js sends emails based on STMP protocol and EWS protocol

Table of contents 1 Node.js method of sending ema...

Detailed explanation of MySQL alter ignore syntax

When I was at work today, the business side asked...

Detailed explanation of docker entrypoint file

When writing a Dockerfile, include an entrypoint ...

Vue implements a simple magnifying glass effect

This article example shares the specific code of ...

How to modify mysql to allow remote connections

Regarding the issue of MySQL remote connection, w...