【JS】Five minutes to understand closures

After understanding js scope and scope chain, (https://blog.csdn.net/timcope/article/details/80103538) we can explore closures.

function a (){
   function b(){
      console.log(aaa);
   }
   var aaa = 123;
   return b;
}
var demo = a ();
demo();

[The concept of closure]

The above code is a typical closure. When the inner function of a function is saved to the outside, a closure must appear. The definition of closure has always been very vague in js learning. It can be said that everyone's understanding of closure is different. I think closure is the product of scope. Let's think that closure means one can access another function. A function of a variable in scope .

[Why closures are formed]

When a function is defined, a will generate an execution context, a.[[scope]] ->scope chain[0]->Global Object

Next, the a function executes a.[[scope]]->scope chain[0] ->Activation Object  scope chain[1]->Global Object .

When b is defined, since b is defined in function a, it can access the scope of a, so that the execution context generated by the scope chain b of a born on the scope chain of b is b.[[ scope]]->scope chain[0] ->Activation Object (this is an AO for a scope chain[1]->Global Object .

When executing to return b, b is saved to the outside and accepted by the demo variable.

After a is executed, it will destroy its own execution context, that is, destroy a.[[scope]]->scope chain[0] ->Activation Object.

But the b function is saved to the outside and executed, and its scope chain has b.[[scope]]->scope chain[0] ->Activation Object (b's AO)->scope chain[1] ->Activation Object (this is the AO of a)  scope chain[2]->Global Object

That is to say, when the b function accesses the aaa variable, it will find the variable aaa in the a function with a value of 123 along the scope chain; an external function accesses a variable inside a function, which is a closure. The essence is that the closure causes the original scope chain of a to not be released.

[Hazards of Closures]

We often say that closures will cause the original scope chain to not be released, resulting in memory leaks. What is a memory leak? A memory leak refers to a variable that you do not use (can not access), which still occupies the memory space and cannot be used again. We can find that there is no memory leak in the closure above, because the aaa variable is what we need. When there are other variables we don't need in the a function, this is called a memory leak.

[The role of closures]

1. Encapsulation and attribute privatization can be achieved (I will explain this later)

2. Modular development to prevent global variables (we will talk about it later when we write about modularization)

3. It can be cached (such as the aaa variable in the above example, it has not been cleared, but has been kept in the computer memory)




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325642058&siteId=291194637