Closed packet parsing in JavaScript

Source: Internet
Author: User

have been learning JavaScript for some time, in this time, has felt the various charm of JavaScript, this is a magical language, but also is a gradual improvement of the language, I believe in the gradual revision of everyone, the language will gradually improve, in the last essay, And you share the JavaScript in the unique class of inheritance, today, and share with you I have been doing these days, but still do not very thorough closure problem, for a beginner, the closure of JavaScript is undoubtedly a difficult point, And that's one of the things we have to master, so today I'm going to share with you some of the insights I've learned about closures and the corresponding understandings, first of all, we have a variable in a function: Code 1

1 Function people () {2     var age = 12; // There is a variable in the function 3    function // in the function we define a self-calling function 4           alert (age); 5     })(); 6    7 }    

In the function people, there is the variable age, you should have been aware of JavaScript specific variable scope of the problem, the function itself is a scope, function inside can access the outside of the variable, and the function outside does not access the variables inside the function, so we have encountered a problem What happens if we want to get the variables in the function? As shown in code 1, since the calling function is in people, so it can access the variables outside of it, so since the calling function can access the age, then we would like to return this self-invoking function is not OK? Code 2:

1 functionpeople () {2      varAge = 12;3      return function (){4 alert (age);5      }6  }7  varXiaoming =Newpeople ();8Xiaoming ();//The text box 12 appears, indicating that an internal variable of age is called outside of people

Well, in this way, we get the variables inside the function, then this is called the closure (closure), the upper function is its first function, can be outside the function through the closure of the function inside the variable, from the shape, the closure is the function inside and then define a function and return, From the book as well as the various blogs on the explanation of the closure of the various, I understand the closure of the whole function is equivalent to a house, the house has no door, there is only one skylight, we can not see the house in the bottom of things, and closures are like a ladder, Let us climb up can see through the Skylight house inside the thing, is the connection function outside and inside of a bridge, closures for our convenience is self-evident, however, things always have the opposite side, closures have his good, of course, there is its bad, now, we can first use closures to do a cumulative example: Code 3 :

1 functionfunc () {2      varcount=10;3      return function(){4          return++count;5      }6  }7  varSS =Newfunc ();8Alert (SS ());//Popup9Alert (SS ());//pop Up

With code 3, we can see that every time the closure returned in the Func is called, Count is cumulative, and there is definitely a lot of confusion in our mind, not the good function is a scope? Execute function func The variables in the body should not exist. How does it accumulate at every call? This is the second function of the closure, and when the closure is executed outside the function body, its body holds the entire execution environment of the function of its parent class and the variables it calls in the body, and then their relationship is like we build a house, and Func is like a foundation, SS is our roof, and we stand on the roof, So is the foundation going to disappear? Obviously not, this is the closure of a merit, but also a drawback, is that it will be an internal variable has been put into the memory can not be released, there may be a memory leak, but this is one of its advantages, you can lengthen the scope chain, But this feature is a frequent error in the For loop:

Code Listing 4:

1 functionfunc () {2      varArr=[];3       for(vari=0;i<5;i++){4arr[i]=function(){//note here that a function is stored in the array5              returni;6          }7      }8      returnarr;9  }Ten  varArr=func (); One   for(vari=0;i<5;i++){ AConsole.log (Arr[i] ());//This will return five X 5 -}

Will we feel the same confusion at this point, should this not return 0-4? This is the closure in the application of a pit, at this time, we can understand that when the first closure function is stored in the arr[0], the function is not executed, then the closure of a link in the store I, It also does not know what the value of I is, when the Func is executed, then the closure is stored in a scope link of I, when executing the function in the ARR array, because the function in the array does not have the variable i, so it will go up one level to find, then, it found the Func, In this case, the value of I in Func has changed to 5, so each number of outputs is 5. Then there are consequences, there is good, there is bad, there are mistakes we have a way to solve:

1 functionfunc () {2      varArr=[];3       for(vari=0;i<5;i++){4Arr[i]= (function(num) {5              returni;6}) (i);//The self-calling function is then used7      }8      returnarr;9  }Ten  varArr=func (); One   for(vari=0;i<5;i++){ AConsole.log (Arr[i]);//This will output 0-4 -}

Modified method One: is to change the closure to a self-calling function at this point, the incoming arr[i] is no longer a function, but the passed parameter I, and so on, we can also return a closure, just to let the closure of a certain value, but not a variable:

1 functionfunc () {2      varArr=[];3       for(vari=0;i<5;i++){4arr[i]=function(num) {5              return function(){6                  returnnum;7              }8 } (i);9      }Ten      returnarr; One  } A  varArr=func (); -   for(vari=0;i<5;i++){ -Console.log (Arr[i] ());//This will output 0-4 the}

When using this scheme, the current value of the loop variable is bound with the parameters of the newly created function, regardless of how the loop variable is subsequently changed and the value of the function parameter is bound to the same, so when using closures, try not to put the variables that will change later in the closure. At the same time, Closures not only change the scope of the variables used in the function, but also change the scope of this:

1  varName= "KKKK";2 functionpeople () {3      This. name= "Lala",4      This. getname=function(){5         return function(){6Alert This. Name)7         };8     }9 }Ten varxiaoming=Newpeople (); OneXiaoming.getname () ();//This will pop up KKKK

At this point, when we return a closure, the object that holds this binding in it is the window, not the people, in which the principle is: My understanding is that when you return a function, it is enclosed in which the function is not executed, so the point of this is not determined , when the closure is executed outside the object, this goes back to the object it is pointing to, and then it points to the window, which we can use to capture this:

1  varName= "KKKK";2 functionpeople () {3      This. name= "Lala",4      This. getname=function(){5         varthat= This;6         return function(){7 alert (that.name)8         };9     }Ten } One varxiaoming=Newpeople (); AXiaoming.getname () ();

Then again the output is Lala, of course, we can not only use this way to capture this, we can also use the object we have learned to impersonate the method to execute the function:

1 varName= "KKKK";2 functionpeople () {3      This. name= "Lala",4      This. getname=function(){5         return function(){6Alert This. Name)7         };8     }9 }Ten varxiaoming=Newpeople (); OneXiaoming.getname (). Apply (xiaoming,[]);

Using this method can also achieve the purpose we want, and we can also use call. Here, we should have a preliminary understanding of closures, the closure of this kind of things, may understand the time to understand some, but when we actually apply, it may feel very difficult at first, But we should believe that practice makes perfect, and the closure of this kind of thing, maybe we use every day, but for its intrinsic principle or smattering, this must do more exercise, do more experiments, when you have doubts, put the code to run a bit, look at the results, and then think about why this is the result, everyone, Come together!

This blog is the original blogger, if there is reproduced please indicate the source!

Closed packet parsing in JavaScript

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.