A programming language

One of the most basic features of almost any programming language is the ability to store values in variables and then access and modify them. So where are these variables stored? How does the program find them? The solution to these problems is to design a set of rules that frame these variables and allow them to be modified or accessed. This set of rules is called scope.

Definition of scope

Know your enemy and you can win a hundred battles. In order to fully learn about scope, we must clearly know what its definition is. So what is the definition of scope? First, we will introduce the concept of scope:

[[scope]]: Every JavaScript function is an object. Some properties of the object are accessible, but some are not. Scope is one of them

[[scope]] is what we call a scope, which stores a collection of run-time contexts

Runtime context

When a function executes, it is common to have an internal object called the execution-time context. An execution-time context defines the context in which a function is executed. Each time a function is executed, the corresponding execution context is unique. Therefore, multiple calls to a function result in the creation of multiple execution contexts, which are destroyed when the function completes execution. Take a look at the following code:

function a() { function b() { var b = 234 console.log(a); //123 } var a = 123 console.log(a); //123 b() } var glob = 100 a()Copy the code

Function (b); function(b); function(b); function(b); There are obviously three execution contexts: the global GO:{}, the execution context of a function AO:{}, and the execution context of b function AO:{}. So what happens during execution? At this point we need to introduce the scope chain again

The scope chain

[[scope]] stores a collection of execution context objects in a chain called the scope chain

The illustration

First of all, when function A is defined, function A has a scope attribute, which has a scope chain array scope chain[]. The subscript 0 represents the global context GO:{}, and 1 represents the context AO:{} of a. Function a (); function A (); function A (); glob (); function A ()

When function B is defined, it will also have a scope attribute, whose scope chain[], subscript 0 represents the global context GO:{}, 1 represents the context AO:{} of A, and 2 represents the context AO:{} of B. When function B is executed, it brings the definition of variable B and the printing of variable A. The context of the b function is destroyed after it finishes, and the context of A is destroyed after the execution of A.

From a js small white opinion, if there is any mistake, please point out in the comments below, thanks!