The concept of execution context

Execution context: The environment in which the javascript code is parsed and executed.

The type of execution context

Execution contexts fall into three types:

1. Global execution context

  • After the js code starts running. First enter the global execution context, where JS code that is not in any function will be executed
  • There is only one global execution context in a JS program. When created, it hits the bottom of the stack and only pops up when the program ends
  • The global execution context does two things. Create a global object. 2. Point this to the global object
  • In the browser environment, the global object is Window; in the Node environment, the global object is global

2. Function execution context

  • A new function execution context is created each time a function is called. Each function has its own execution context, but it is created only when it is called
  • The life cycle of a function execution context is divided into two phases. Create and execute
  • Each execution context has the following three properties
    • VO variable object
    • Scope chain Scope chain
    • this

Eval Execution context

  • The execution context generated when the eval function is executed.

Execution context stack

The execution context stack is a lifO data structure, and the execution flow is as follows

  • The global execution context is first created and pushed to the bottom of the stack
  • Each time a function is called, the function execution context is created for the function. And push it to the top of the stack
  • When the function completes execution, it is popped from the execution context stack, and the JS engine continues to hold the function at the top of the stack.

For example, the stack changes when the following function is executed:

function fun1(){
    console.log('func1')
    fun2()
}
function fun2(){
    console.log('func2')
}
fun1()	
/* * fun2 * fun1 fun1 fun1 * global => global => global => global => global */
Copy the code

Execute the context life cycle

The variable object VO and the active object AO

Before WE talk about the life cycle. We need to know about an object, VO and AO

Variable object VO:

  • Used to store execution contexts that can be accessed. But cannot be identified by the delete function.
  • Arguments objects, parameter key-value pairs, function declarations, variable declarations, and this

Active object AO:

  • It can be thought of as an object created when a function is invoked. Used to access the identities stored in the VO object.

Variable objects in the global context:

  • That’s the global object
  • Initialization: Initializes a set of primitive attributes: Math, String, Date, Window, etc
  • The window object refers to the global object in the browser, and this refers to itself in the global environment

Create a stage

The execution context at this stage does the following

  • Create scope chains
  • Create the active AO from the variable object VO,
    • Start by creating the Arguments object
    • Creates a key-value pair for the parameter argument
    • Creating a function declaration (classic interview question: Why is the function declaration early?)
    • Create variable declarations (Classic interview question: Why do variable declarations improve?)
  • To create this

Execution phase

  • Variable assignment. Function references that perform other code logic
  • When the execution is complete. Execute the context out of the stack and wait for the garbage collection mechanism to collect

For example

function a(name, age){
    var a = 1
    function c(){}
    var d = funciton (){}
    (function e(){})
    var f = function g(){}
}
a('John')
// As shown above.
// The AO objects generated during the creation precompilation phase are as follows
AO = {
    arguments: {0: 'John'.1: undefined.length: 2
    },
    name: 'John'.age: undefined.c: reference to function c(){},
    a: undefined.d: undefined.f: undefined,}// The function expression e is not in AO
// function g is not in AO

// The function executes with the following AO object
AO = {
    arguments: {0: 'John'.1: undefined.length: 2
    },
    name: 'John'.age: undefined.c: reference to function c(){},
    a: 1.d: reference to FunctionExpression "d".f: reference to FunctionExpression "f",}Copy the code

Function declaration advance

We can see from the creation process of the AO object that the AO object scans the function declaration in the function body before scanning the variable declaration. So that’s why there was an early announcement.

Variable ascension

The AO object is created with the variables inside the function declared in advance. The sequence of assignments that begins during the execution of a function.

Lexical environment and variable environment

Two concepts of lexical environment and variable environment are proposed in ES6. The main task is to perform the context creation process.

LexicalEnvironment

A lexical environment is a structure that contains an implicit relationship between the identifier => variable.

There are two components in the lexical environment:

  • EnvironmentRecord: The actual location where variable and function declarations are stored
  • References to external environments (Outer) : The currently accessible external lexical environment

Lexical environments fall into two types:

  • Global context: The global execution context, which has no reference to the external environment and has a global object window with associated methods and attributes eg: Math,String,Date, etc. We also have user-defined global variables and point this to the global object.
  • Function environment: Variables defined by the user in the function are stored in the environment record. A reference to an external environment can be a global environment or an external function environment that contains internal functions. Contained in the environment record. Variables declared by the user. Function. Arguments objects are also available.

The example lexical environment is shown in pseudocode as follows:

GlobalExectionContent = {
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Object".// The remaining identifier
    },
    Outer: null,
  }
}

FunctionExectionContent = {
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative".// The remaining identifier
    },
    Outer: [Global or outer function environment reference].}}Copy the code

VariableEnvironment

The variable environment is also a lexical environment. In ES6, LexicalEnvironment differs from VariableEnvironment in that the former is used to store function declarations and variable let and const bindings, while the latter is only used to store variable var bindings.

Use the following code as an example:

let a = 20;  
const b = 30;  
var c;

function add(e, f) {  
 var g = 20;  
 function c(){}
 return e + f + g;  
}

c = add(20.30);
Copy the code

In the precompilation phase. The resulting lexical and variable environments are as follows

GlobalExectionContent = {
  thisBinding: Global,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Object".a: <uninitialied>,
      b: <uninitialied>,
      add: <func>
      // The remaining identifier
    },
    Outer: null,},VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Object".c: undefined.// The remaining identifier
    },
    Outer: null,
  }
}

FunctionExectionContent = {
  thisBinding: Global,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative".arguments: {
        0: 20.1: 30.length: 2,},e: 20.f: 30.c: reference to function c(){}
      // The remaining identifier
    },
    Outer: GlobalLexicalEnvironment,
  },
  VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative".g: undefined.// The remaining identifier
    },
    Outer: GlobalLexicalEnvironment,
  }
}
Copy the code

We find that variables declared using let and const have unassigned initial values when the lexical environment is created. Variables defined using var are assigned undefined when the variable environment is created. This is why const, let, and var variables fail when they are called to declare money.

This is true by analogy with our execution context

Code execution phase

The flow of execution at this stage is the flow of function execution. Assign values to variables, and perform other logical code.

Follow public account

Like the students can pay attention to the public account