This is the 15th day of my participation in the August More Text Challenge

scope

In the last review of JS execution Context, we talked about a concept called execution context, where we talked about global, function, and eval environments. The context is actually scope, so here is a bit of nagging, scope has the following:

  • Global scope: Same as the GO object above
  • Function scope: The VO object at each execution
  • Block-level scope (added after ES6) : after ES6, the keyword that defines a variable becomesLet and const, let and const have their own rules,Details see.

Since variables are scoped and functions are scoped, how do they connect to form a scoped chain?

The scope chain

Js code execution creates the corresponding scope (execution context) in the Call Stack, and then a VO in each context holds the variables of the current scope. However, if a function is created in VO, then an additional genus [[scoped]] points to VO (AO) at the top of the stack;

The above paragraph is a little difficult to understand, let’s take an example, draw a picture to see understand.


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

function B(){
 var a = 123;
 var C = A;
 C();
}
B();
Copy the code

To understand this example, let’s draw a picture.

Each frame in the figure above can be understood as something the code does at run time.

Function C refers to the address of function A. Function A is created in the global scope, so function A[[scoped]]Is pointing toGO object. The red line is shown below:

C –> A –> GO, such as: C –> A –> GO such scope-pointing form, we call it the scope chain. Lookups are also lookups strictly along the scope chain.

Results:

closure

In the above example, our function A is stored inside function B (which uses A reference address inside), but in fact function A is in A global scope.

  • In a broad sense,Functions use functions inside functions, and inside functions use variables outside functions. In the example aboveFunction BYou form a closure.
  • In a narrow sense: a function uses external variables inside, and a function is called in another scope to form a closure.

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

function B(){
 var a = 123;
 var C = A;
 C();
}
B();
Copy the code

Closures are actually quite common in our development. There is also a problem with closures: memory leaks, which is not true. A memory leak is when variables in memory are not accessible and cannot be cleaned up by garbage collection. You can find the variable A in the example above. There’s a lot of ways we can find him.

Some of you might want to say, well, the closure that we see is something like this, right?

Function A () {var A = 1223; return function(){ console.log(a) } } var afunc = A(); afunc();Copy the code

The above code creates function A, then executes function A, and then returns A function. As soon as the function is executed, the Call stack is cleared.

This article uses the article synchronization assistant to synchronize