Execution context

define

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

We use functions all the time, we use functions to do all kinds of logical processing, we can call each other, and when the function call ends, the program will go back to the function call through the execution context.

Execution context can be divided into global execution context and function execution context. Both execution contexts have two phases: creation phase and execution phase

1. Global execution context

  1. Create a stage:Created before global code is executed.
  • Create global execution objects: window on the browser side, Global in Node
  • Perform on global dataPretreatment:
    • Var global ==>undefined, added as window property (variable promotion)
    • Function declared global function ==> assignment (fun), added as window method (function promotion)
    • Make sure this refers to ==> assign (window)
  1. Execution phase: Executes global code

The global context is pushed to the bottom of the execution stack (described below), and the code is executed line by line until the calling part of the function is entered into the execution context of the function. After the function is executed, the function is removed from the stack, and so on, when the global code is executed, the global execution context object is destroyed

2. Function execution context:

Each time a function is called, a function execution context is created

Each invocation of a function’s data is independent of each other and belongs to its own execution context object

When the function call ends, the execution context object is destroyed

  1. Creation phase: When a function is called, the execution context of the function is created before the statements within the function are executed

  2. Preprocessing the data inside the function:

    • Assign a value (argument) to the parameter as a property of the execution context object
    • Assign arguments to a value (the collection of arguments) as a property of the execution context object
    • The variable declared by var is promoted (assigned to undefined) as a property of the execution context object
    • Function promotions (values) declared by function are used as methods of executing context objects
    • Make sure this points to the object calling the function, and call this globally directly to the window
  3. Execution phase: Execute statements within a function

3. The execution stack

Stack storage structure: first in, last out

Used to store the execution context

The specific execution process 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

4. Perform the context lifecycle (see 1.2 Understanding the Creation phase

The ES5 specification removes variable and active objects from ES3 and replaces them with LexicalEnvironment Component and VariableEnvironment Component.

Creation phase:

The execution context at this stage does the following

  1. Determine the value of this, also known as this Binding
  2. The LexicalEnvironment component is created
  3. The VariableEnvironment component is created

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

Destruction of phase

scope

The concept of scope can be divided into global scope and block-level scope (including function scope)

1. Global scope

Variable promotion:

  • Variables declared using the var keyword are declared before any code is executed
    • The output of a is undefined
  • However, if the var keyword is not used, variables are not declared ahead of time
    • If you use let keyword: errorCannot access before initialization

Function declarations are advanced

  • Functions created using function declarations are created and stored before all code is executed
  • Functions created with function expressions are not created in advance, and the function variables are undefiend but cannot be called

2. Function scope

1. Define ⭐

The function itself is also a value and has its own scope. Its scope, like a variable, is the scope in which it is declared, independent of the scope in which it is run

var a = 1;
var x = function () {
  console.log(a);
};

function f() {
  var a = 2;
  x();
}

f() / / 1
Copy the code

In the above code, function X is declared outside of function F, so its scope is bound outside. The inner variable A is not evaluated inside function F, so it prints 1 instead of 2.

The scope in which a function executes is defined, not invoked.

2. Scope chain:

var a=10;
function fun1(){
  var b=20;
  var a="fun1 a"
  function fun2(){
    console.log(a)
  }
  fun2()
}
fun1();
Copy the code

3. Omission of keywords

var c=33;
function fun(){
  console.log(c);
  c=10
}
fun();
//console.log(c);
Copy the code
  • c=10Output 33, no variable promotion since var is not defined, find the global C output
  • var c=10 Output undefined variable promotion
  • let c =10An error
  • var cOutput is undefined

In the code above, console.log(c) in the global results in 10. Variables assigned directly to functions become global variables

4. Parameters are equivalent to declaring variables in a function scope

var e =23;
function fun(e){
  console.log(e)
}
fun();
Copy the code

The function is called with undefined. Passing in the parameter e is equivalent to declaring var e in the function scope.

3. Block level scope

{} creates block-scope, and variables with block-scope are declared with let or const

  1. If statement
  2. A switch statement
  3. For statement
  4. While statement
  5. Write code directly in {}

4. The closure

A function cannot read a variable from outside the function (scope chain). If f2 is nested inside the function and you want f2 to read a variable from f1, you can solve this problem by using f2 as its return value, in which case F2 is the closure:

function f1() {
  var n = 999;
  function f2() {
    console.log(n);
  }
  return f2;
}

var result = f1();
result(); / / 999
Copy the code

Closures are useful for three reasons:

  • One is to read variables inside the outer function,
  • Another is to keep these variables in memory at all times, that is, a closure can keep its birth environment alive.
  • Closures are also useful for encapsulating the private properties and methods of an object. Nguyen other JS

3. The relationship between scope and execution context ⭐

  • The function scope isIn the function declarationThe function execution context isin A function callWhen determining
    • But variables in a function are created at the time of the call

The difference between:

  1. Different creation points:
scope Execution context
Function: When the function is definedCreate the function scope Function callCreate execution context
Global: Created when the page opens After the global scope is determined, created before code execution
  1. Different attributes:
  • The scope is static and exists as long as the function is defined and does not change
  • The context is dynamic

References:

  • JS modern
  • Nguyen other javascript.ruanyifeng.com/grammar/fun…
  • FuMing: learn. Fuming. Site/front – end/J…
  • Take you thoroughly understand the execution context www.dazhuanlan.com/2019/12/16/…