JavaScript creates executable contexts during execution. (Each function execution creates such an executable context.)

The lexical environment of each executable context contains a reference to the external lexical environment, through which variables and declarations in the external lexical environment can be retrieved.

These references are concatenated all the way to the global lexical environment, forming a chain structure called the scope chain.

In short: a function can access variables in its outer scope, and an outer function can access variables in its global scope,

The chain structure of variable scope access is called scope chain.

let num = 1

function fn () {
  let a = 100
  function inner () {
    console.log(a)
    console.log(num)
  }
  inner()
}
fn()
Copy the code

The following is a call stack consisting of multiple executable contexts:

  • The bottom of the stack isGlobal executable context
  • Global executable contextThere are more than oneFunction executable context
  • Each executable context contains references to other external executable contexts untilGlobal executable contextWhen it refers tonull

Js global has a global executable context, each function call, with the executable context of the function, will enter the JS call stack

Each executable context has a reference to the lexical scope of the external context, and the external context has a reference to the lexical scope of the external context

=> forms the scope chain