JS----Deep Understanding closure

Source: Internet
Author: User

The closure is a bit more difficult to understand in JS, especially for those who do not have the basis for programming.

In fact, the closure should pay attention to a few, if you understand that it is not difficult to conquer it. Let's talk about some basic principles of closures.

The concept of closures


A closure is a combination of a function and a scope object in the function being created. (Scope object will say below)

The popular point is that "as long as one or more functions are nested within a function, then we can call them a closure." ”

Similar to this:

1 function A () {2   var i = 5; 3   return function () {4     console.log (' i = ' +i); 5   }6}78var a = A (); 9 // i = 5

The principle of closure

  1. If a local variable of the external function is called by the closure function, it will not be reclaimed immediately after the external function is executed.

We know that in any language, there is a garbage collection mechanism in the operating system that reclaims excess allocated space to reduce memory. And the life cycle of a function starts from the call, and when the function call is complete, the local variables inside the function are recycled by the recycle mechanism.

In the example above, when our external function A is called, the local variable i in a is supposedly recycled by the operating system and does not exist, but when we use the closure result is not the case, I will not be recycled. Just think, if I was recycled, then the returned function is not printing undefined?

  Why I have not been recycled?

When JavaScript executes a function, it creates a scope object, saves the local variables in the function (the parameters of the function are also local variables), and is initialized along with the variables that pass into the function.

So when we call a, we create a scope object, we call it AA, then this AA should be this: AA {i:5;}; After the A function returns a function, a executes. The AA object should be recycled, but because the returned function uses the AA attribute I, the returned function holds a reference to the AA, so AA is not recycled.

So understanding the scope object will understand why the local variables of the function will not be recycled as soon as the function call is complete when the closure is encountered.

One more example:

1 functionA (age) {2   varName = ' Wind ';3   varSayHello =function() {4Console.log (' Hello, ' +name+ ', you're ' +age+ ' years old! ');5   };6   returnSayHello;7 }8 varWind = A (20);9Wind ();//Hello, Wind, years old!

Can you tell what it's scoped object WW is?

ww{age:20; Name: ' Wind ';};

  2, each call to the external function to produce a new closure, the previous closures still exist and do not affect each other.

  3, the same closure will retain the last state, when it is called again on the basis of the previous.

Each call to an external function produces a different scope object, you can think of the above example, each time you pass in the parameter age is different, so that every time the object generated is different.

Each time an external function is called, a new scope object is generated.

1 functionA () {2   varnum = 42;3   return function() {Console.log (num++); }4 }5 varA =A ();6A ();// the7A ();// +8 9 varb = A ();//call A () again to form a new closureTenb ();// the

This code allows us to find two things , one, when we call two A () consecutively, Num will be added on the original basis. Indicates that the same closure will remain in the last state and will be performed on the previous basis when it is called again. Second, our B (); The result is 42, which indicates that it is a new closure and is not affected by other closures.

We can think like this, like we blow bubbles, every time I blow (call an external function), a new soap bubble (closure) is created, and multiple soap bubbles can exist at the same time and no interaction between the two bubbles.

  4. Multiple functions "die" that exist in an external function

The following three functions are declared at the same time and can be accessed and manipulated on the properties (local variables) of the scope object.

varfun1, fun2, fun3;functionA () {varnum = 42; Fun1=function() {console.log (num);} Fun2=function() {num++; } Fun3=function() {num--; }   }a (); fun1 (); // thefun2 (); fun2 (); fun1 (); // -fun3 (); fun1 (); // +varOld =fun1;  A ();   Fun1 (); // theOld ();//43 previous closure of FUN1 ()

Because a function cannot have more than one return value, I used a global variable. Again, we can see that a new closure was generated when we called a () a second time.

When a closure encounters a loop variable

When we talk about closures, we have to say that when a closure encounters a loop variable, look at the following code:

1 functionBuildarr (arr) {2     varresult = [];3      for(vari = 0; i < arr.length; i++) {4         varItem = ' Item ' +i;5Result.push (function() {Console.log (item + "+arr[i])} );6     }7     returnresult;8 }9 Ten varFnlist = Buildarr ([]); OneFnlist[0] ();//item2 undefined AFNLIST[1] ();//item2 undefined -FNLIST[2] ();//item2 undefined

How could that be? The three outputs we envision should be item0 1, item1 2, item2 3. Why is it that the result is returned with three item2 undefined stored in the resulting array?

It turns out that when a closure encounters a loop variable, the value of the variable is stored uniformly after the loop, and with our example above, I is the loop variable, and when the loop is all over, I is exactly 3 after i++, and arr[3] is no value, so for undefined, Some people will wonder: Why is the value of item item2, shouldn't it be item3? Note that at the time of the last loop, which is i = 2, the value of item is ITEM2, when the I++,i = 3 loop condition does not meet the end of the loop, the value of item at this time is already set, so the arr[i at this time] is arr[3], and item is ITEM2. Does that make sense? If we change the code to that, it makes sense:

function Buildarr (arr) {    var result = [];      for (var i = 0; i < arr.length; i++) {         function() {console.log (' item ' + i + "+ arr [i])});     return result;} var fnlist = Buildarr ([]); fnlist[1] ();  //   item3 undefined

So the question is, how to correct it? And look at the code:

1 functionBuildarr (arr) {2     varresult = [];3      for(vari = 0; i < arr.length; i++) {4Result.push ((function(n) {5            return function() {6               varItem = ' Item ' +N;7Console.log (item + "+arr[n]);8            }9 }) (i));Ten     } One     returnresult; A } -  - varFnlist = Buildarr ([]); theFnlist[0] ();//item0 1 -FNLIST[1] ();//item1 2 -FNLIST[2] ();//item2 3

We can bind I with a self-executing function so that each state of I is stored and the answer is the same as we expected.

So later in the use of closures to meet the loop variable we have to habitually think of using self-executing function to bind it.

The above is my understanding of closures, if there are any comments or suggestions I hope we can communicate in the comment area. Thanks, mutual encouragement.

JS----Deep Understanding closure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.