First, understand JS

As we know, JS is a scripting language, an interpreted language, which can be converted and executed at the same time. It does not generate executable files and supports cross-platform execution, and it can do so mainly thanks to the interpreter, the middle layer.

By cross-platform, I mean the source code can be cross-platform, not the interpreter. Different interpreters have been developed for different platforms so that they follow the same functions, the same syntax, and the same functionality.

The V8 engine in Chrome acts as an interpreter, interpreting and executing JS source code.

Execution context

The execution context is simply the JS code running environment, the global execution context is the global environment, the function execution context is the environment within the function.

To run code must first enter the global execution context.

Execution contexts are divided into:

Global execution context: There is only one global execution context, and code that is not in a function is in the global execution context.

Function execution context: Each function has its own function execution context, but the function execution context is created only when the function is called. There is no limit to the number of function execution contexts.

Eval execution context: rarely used.

Phase of executing the context

The execution context is divided into three stages: creation, execution and reclamation. The creation stage is divided into three steps:

  1. Variable object (VO) : For variable promotion, function declaration, this step can also be called precompilation, in the global environment VO can also be considered precompiled to create GO.

  2. Scope chain: The scope is created after the variable object is created. The scope is used to resolve the variable. If the variable cannot be found in its own scope, it is searched from its parent scope, and so on, until it is found or reaches the outermost scope.

  3. This: Determines what this refers to. Globally, this refers to the window. Of course, the value of this is determined at execution time.

The execution phase of the execution context: assigning values to variables, calling functions, executing code.

Execution context reclamation phase: The execution context is ejected from the stack, waiting to be reclaimed.

Execution stack

It can be thought of as a stack structure, following the principle of “first in, last out”. The execution context created must be placed on the execution stack before it is executed.

Execute the stack running process

  1. The browser starts by executing code to create the global execution context, pushing it to the bottom of the execution stack.

  2. When a function call is encountered, the function execution context is created and pushed on top of the global execution context. When a function call is encountered during function execution, a new function execution context is created and pushed on top of the previous function context. When the execution of a function is complete, the execution context of the function is removed from the execution stack, waiting to be reclaimed.

  3. The browser only invokes the execution context at the top of the stack.

  4. The global execution context pops up when the browser is closed.

Code demo

Let’s demonstrate this process with a simple piece of code

var a= 3
var b = 3
function output1() {
    console.log(a)
    output2()
}

function output2()  {
    console.log(b);
}
output1()
Copy the code
  1. The browser creates the global execution context and pushes it down to the bottom

  2. The function declaration does not create the function execution context until the output1 function call creates the function execution context of the same name and pushes it onto the stack

  3. When an output2 call is encountered during a call to the output1 function, create an output2 execution context and continue pushing.

  4. When output2 completes, it is popped off the stack, giving control to the context below it, the context in which the output1 function is executed.

  5. Output1 also completes and pops up the stack, giving control to the global execution context until the global pops up as well.

Iv. Variable promotion/precompilation

Precompilation occurs before a function is executed, and the code is scanned for function declarations and variable declarations.

Variable promotion occurs during the creation of the execution context. Variable and function declarations are promoted.

As far as I’m concerned, the difference between precompilation and variable promotion is not that great, but precompilation is just another name for variable promotion.

Precompilation process:

Precompilation occurs in the global trilogy

  1. createGOObject (in the global execution contextVO = GO)
  2. Find the variable declaration and treat the variable declaration asGOThe property name of the object to which the value is assignedundefined
  3. Find the function declaration in the global and use the function name asGOObject property name, value assigned to function body

Precompilation occurs within a function in four tetralogy

  1. To create aAOActivation Object
  2. Find the parameter and variable declarations and treat the parameter and variable declarations asAOThe property name of the object, with the valueundefined
  3. Unify arguments and parameters
  4. Find the function declaration in the function body and use the function name asAOObject property name, value assigned to function body

Precompilation rules:

  1. Variable declaration promotion: For variables defined with VAR, the variable is promoted to the top of its scope and initialized as undefined during precompilation.

  2. Function declarations are promoted: function declarations are also promoted, but the whole function is promoted, creating a function variable and storing everything in the function, but not executing it.

  3. Function declarations have higher precedence. When both function declarations and variable declarations are promoted, function declarations override variable declarations of the same name, but variable declarations can be reassigned.

  4. Assignment statements such as a = 2 are not declarations. They are run at run time and create variables that are global in scope.

Code demo

         var a = 1
         function fn(a) {
             var a = 2
             function a() {}
             var b = a
             console.log(a);
            
        }
         fn(3)     //2
Copy the code
  1. Create the GO object, promote the variable a, initialize it as undefined, then declare promote the fn function, promote the whole fn function, but do not execute, then enter the code execution, a is assigned a value of 1, next call the function fn.

  2. When fn is called, create an Ao object, raise the parameter and variable A and initialize it to undefined, and raise variable B and initialize it to undefined.

  3. Finally, function A is promoted. Due to the principle of function preference, a is initialized as function A at this time, and the code execution stage is entered. A is assigned the value of 2, b is assigned the value of A, that is, 2, and finally output a is 2.

Result of creating GO and AO objects

    go:{
        a: undefined  1
        fn: function

    }

    ao: {
        a:undefined 3  function  2
        b: undefined  2 
    }
Copy the code

Five, analyze the code operation steps

How does the code work step by step

var a = 1 function fo(a) { var b = 2 console.log(a); Function fo1() {console.log(b); } var c = fo(2) c()Copy the code
  1. Create global execution context, push it to the bottom of the stack, context creation stage — create variable object/precompile stage (variable declaration, function declaration promotion), create scope chain, this binding.
  • creategoObject,a.cPromote and initialize toundefined.foFunction declarations promote the entire function body, saving them all ingoObject, this refers to the window.
  1. The global execution context enters the execution phase.
  • ingoObject assigns a to 1, and setscThe assignment forfo(2)When a function call is encountered, the function execution context is created.
  1. createfoThe function execution context is pushed onto the execution stack with the global execution context below it, and the function execution context creation stage is followed by the same three steps.
  • createaoObject,Type a, b,Initialized toundefined, and then unify the parameter and argument, i.eaGive it a value of 2, and finally do the function declaration promotion to save them all inaoIn the object.
  1. foThe function execution context enters the execution phase.
  • willbAssign a value of 2, and printaBecause the creation phase was precompiled, at this timeaValue of 2, so the output 2, encounteredreturnNeed to return, willfo1Everything inside the function is stored info1Where the function returnsfoThe call ends. Normally, it willfoThe execution context pops up the execution stack, but becausereturnPhi is a function,Create closures so that the scope is not deleted and the variables inside are still available.
  1. The fo function call ends, the return value is a function fo1, assign it to C, so in the global context, it is no longer fo1, it is called C, next, call C.

  2. When a function call is called, create the c function execution context, push the execution stack, context creation stage — create variable object, create scope chain, this binding.

  • createaoObject, there is only one output statement, so there is no variable, function promotion.
  1. fo1Execution phase, as called externallyfoThe internal function of the closure mechanism resultsfoScope is not released, so when printing b, look up the parent scope and find at this pointbIs 2, output 2.
  • callfo1End, pop up the function execution stack, and finally the code execution is finished, the execution stack will be emptied.

Create variable object:

go: {
    a: undefined  1
    fo: function
    c: undefined fo1
}

ao: {
    b: undefined 2
    a: undefined 2
    fo1: function  
}

ao: {
    
}
Copy the code

Six, summarized

This article introduces JS, execution context content, execution stack, variable promotion rules and from the execution context analysis of the code, because I am just a beginner, will summarize their own views record, or hope that you can be many of the correct, like you can point a small 👍, thank 🙇🙇.