Javascript_function (Closure closure)

Source: Internet
Author: User

JavaScript closures (Closure)

A "closure" refers to an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.

It's an official explanation, but it only makes people dizzy. To understand closures, first understand the two points: the scope of the variable and the scope chain, both of which have been described earlier, and gave a simple example, to review:

varcolor ="Blue"; function ChangeColor () {varAnothercolor ="Red"; function Swapcolors () {varTempcolor =Anothercolor; Anothercolor=color; Color=Tempcolor; //inside the Swapcolors function you can access Tempcolor,anothercolor and color    }     //you can access Anothercolor and color here, but you cannot access Tempcolorswapcolors ();} 

The above code, we used to illustrate the scope chain, that is, variables from the inside out to find variables, this simple concept. But now, in turn, what if we need to access the internal execution environment inside an external execution environment?

function F1 () {    var n=999;    function F2 () {        //  999    }    //F2 ();}

The above code is very simple, we call F2 in the F1 () of course we can pop the value of n 999, but if we are in the external global execution environment to get the value of N, what should we do? This is just the question that the external execution environment requires to access the values of the internal execution environment. From the outside, you can use closures to achieve this effect and modify the above code slightly:

 function F1 () { var  n=999 ; //  private variable  //   //    return  F2; //  returns the intrinsic function    //  call function  var  result=f1 (); result ();  //  999  

when one of these intrinsics is called outside the outer function that contains them, a closure is formed (in the example, when the function is called, result actually calls the F2 function, which means that an intrinsic function of F1 is F2 called outside of F1, a closure is created).

Look at a simple example:

function foo () {    var1;    function Geta () {        a++        ; return A;    }     return  =//  return 2//return 3

The above is just an example of closure, which is not common in practical applications. Let's take a look at how closures are encountered in real-world applications.

In the case of an interface there is a set of a tag, click, you want to click on the different a-tag pop-up different results, the code is as follows:

<ul> <li><a href="#"> No. 0 Links </a></li> <li><a href="#"> 1th links </a></li> <li><a href="#"> 2nd links </a></li> <li><a href="#"> 3rd link </a></li></ul>var  as= document.getElementsByTagName ("a"); for(varI=0;i< as. length;i++){     as[I].onclick =function () {alert ("you are now clicking on the first"+ i +"a link"); }}

Above this code estimates everyone has encountered similar, want the effect and the actual appearance of the effect is inconsistent, would like to click on each, pop different I values, but did not expect the last pop I value is 4. This is due to the effect of the variable's scope chain because the anonymous function that the onclick points to is called when the user clicks the a tag. When called, you need to get the value of the variable i, the JS parser will first look inside the anonymous function I, but not defined. I then looked out and found the variable i in the external execution environment, but the I was already looped to 4 because the for loop was already executed when the page was initialized. So what I actually get inside the anonymous function is the value of I in the outer scope chain. To correct this error, I actually pass the value of I to the value of the anonymous function. But anonymous functions cannot pass values. At this time, we can use closures. first create such a function:

function closuretest (num) {    return  function () {        alert (" you are now clicking on the   " link ")    }}

This function directly returns an anonymous function that was previously closed, so when the returned function is received externally, the variable num in the outer function Closuretest will be saved, so modify the previously looped code:

 for (var i=0;i<as. length;i++) {    as [i].onclick=  Closuretest (i);}

Loop inside the onclick call function Closuretest, and passed the parameter I, and Closuretest returned anonymous function, so according to the principle of closure, the incoming parameter I, is stored in the memory, the external access is a different value each time. Of course, you can also directly write the following way:

 for (var i=0;i<as. length;i++) {    as [i].onclick= (function (i) {         return function () {            alert (" you are now clicking on the"" link "   )        }}    ) (i); }

Scenario Two using closures to skillfully pass parameters , such as having such a scene, clicking on a label, and then delaying a popup, and this sentence is passed through the arguments. Let's look at the following code:

<a href="#"> Click I </a>var link = document.getElementById (" MyLink "  = function () {    setTimeout () {        alert (" you clicked on my hyperlink! ") " );    }

This code, that is, click 1 seconds after the pop-up "you clicked on my hyperlink!", of course, here is the words written in the function, if this passage is from the outside? Like there's a way

function someFunction (words) {    alert (words);} var link = document.getElementById ("myLink"= function () {    SetTimeout (someFunction,+);};

Here, the problem is coming. How to pass parameters to somefunction? This can also be used directly with closures

function someFunction (words) {    return  function () {        alert (words);}    ;} var link = document.getElementById ("myLink"= function () {     var saysomething = someFunction (" you clicked on my hyperlink! ") " );    SetTimeout (saysomething,+);};

In the dynamic execution environment, the data changes in real time, in order to maintain the values of these non-persistent variables, we use the closure of this vector to store these dynamic data. This is the function of closures. It is also said that when we encounter data that needs to store dynamic changes or will be recycled, we can solve the problem by wrapping a layer of functions outside to form a closure.

Javascript_function (closed package 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.