Javascript closure (closure)

Source: Internet
Author: User

Closure is translated as a "closure" and it is too academic to wrap it. The following reference books and online resources are briefly discussed (please pay attention to improper understanding ).
1. What isClosure
The official answer: the so-called "closure" refers to an expression (usually a function) with many variables and an environment bound to these variables ), therefore, these variables are part of the expression.
After reading the definition above, if you are not a master, I firmly believe that you will be as angry as I ask: is this TMD a voice?
To understand the closure, orCodeThe code above is the most convincing:

Code
Function Functest ()
{
VaR Tmpnum = 100 ; // Private variable

// Define another function in the function functest as the functest method function.
Function Innerfunctest (
{
Alert (tmpnum ); // Reference the Temporary Variable tmpnum of the outer function functest
}

ReturnInnerfunctest;//Returns an internal function.
}

//Call a function
VaRMyfunctest=Functest ();
Myfunctest ();//100

In the above Code, the annotations have been clearly written. Now we can understand the "closure" as follows ": Define another function in the function body as the method function of the target object (In this example, another function innerfunctest is defined in the function functest as the method function of functest ), The method function of this object references temporary variables in the outer function body. (Closure isIndirectly holding the variable value . The internal function innerfunctest references the Temporary Variable tmpnum of the outer function functest. Note that the temporary variables can include AllLocal variable,ParametersAnd declaredOther internal functions ). When one of these internal functions is called outside of the external functions that contain them, a closure is formed. (In this example, when calling a function, myfunctest actually calls the innerfunctest function, that is, an internal function innerfunctest of functest is called outside functest, and a closure is created ).
2. Two examples of using closures
In the following two examples, one is because the closure causes problems, and the other uses the closure to skillfully bind parameters through the function's scope.
The HTML Tag fragments related to these two examples are as follows:
<A href = "#" id = "closuretest0"> example of using a closure (a prompt will be displayed in 1 second) </a> <br/>
<A href = "#" id = "closuretest1"> Example 1 due to closure </a> <br/>
<A href = "#" id = "closuretest2"> Example 2 due to closure issues </a> <br/>
<A href = "#" id = "closuretest3"> Example 3 due to closure </a> <br/>
(1) problems caused by closures
The preceding HTML Tag contains four <A> elements. Now you need to process the last three specified events. Program To report the order of users on the page when they click. For example, when a user clicks 2nd links, the report "you clicked 1st links" is reported ". To this end, if you write the following functions for adding Event Handlers for the last three links:

Code
Function Badclosureexample (){
For ( VaR I =   1 ; I < 4 ; I ++ ){
VaR Element = Document. getelementbyid ( ' Closuretest '   + I );
Element. onclick =   Function (){
Alert ( ' The '   + I +   ' Links ' );
}
}
}

Then, call this function after loading the page (or an error may be reported:
Window. onload = function (){
Badclosureexample ();
}
Check the running result. Click the last three links. What information is displayed in the warning box? -- All of them are "4th links you clicked ". Are you surprised? Why?
Analysis: this is because element is specified in the badclosureexample () function. the onclick event handler, that is, the onclick anonymous function, is called after the badclosureexample () function is run (when you click the link. During the call, the variable I needs to be evaluated. The parser will first find the variable in the event handler, But I is not defined. Then, go to the badclosureexample () function for search. It is defined at this time, but the I value is 4 (The for loop is stopped only when I is greater than 4 ). Therefore, the value will be obtained-this is the result of variables in the scope of the closure (anonymous function) to use its external function (badclosureexample. In addition, this is because anonymous functions cannot pass parameters (so they cannot maintain their own scopes.
So how can we solve the problem in this example? In fact, there are many methods (You may wish to write it for a while). I think the code is simple and straightforward:

Code
Function Popnum (onum ){
Return   Function (){
Alert ( ' The ' + Onum + ' Links ' );
}
}
Function Badclosureexample (){
For ( VaR I =   1 ; I < 4 ; I ++ ){
VaR Element = Document. getelementbyid ( ' Closuretest '   + I );
Element. onclick = New Popnum (I );
}
}

(2) cleverly use closures to bind Parameters
Or the preceding HTML snippet. When the user clicks the first linkLatencyA warning box is displayed. How can this problem be solved? The answer is to use the setTimeout () function, which calls a function after the specified number of milliseconds, such:
SetTimeout (FIG, 1000 );
However, the problem is that the parameter cannot be passed to the somefunc function. The closure can easily solve this problem:

Function Goodclosureexample (omsg ){
Return   Function (){
Alert (omsg );
};
}

The goodclosureexample function is used to return an anonymous function (closure ). However, we can bind the returned anonymous function to this parameter by passing a parameter for it, for example:
VaR good = goodclosureexample ('the parameter is bound through the closure ');
In this case, the good function bound to the parameter can be passed to setTimeout () for latency warning:
SetTimeout (good, 1000) // The parameter has been bound to good.
Finally, the complete code passed the test:

Code
Window. onload =   Function (){
VaR Element = Document. getelementbyid ( ' Closuretest0 ' );
If (Element ){
VaR Good = Goodclosureexample ( ' This parameter is bound by the closure. ' );
Element. onclick =   Function (){
SetTimeout (good, 1000 ); // 1 second delay prompt
}
}
}

3. Garbage collection principles of JavaScript
(1) in Javascript, if an object is no longer referenced, it will be recycled by GC;
(2) If two objects reference each other are no longer referenced by 3rd, the two referenced objects will also be recycled.
using closures in Javascript often creates difficulties for Javascript garbage collectors. In particular, in the case of complex cyclic references between objects, the judgment logic of garbage collection is very complicated. If it is difficult to do so, there is a risk of Memory leakage. Therefore, use closures with caution. Ms does not seem to recommend using closures.

Related Article

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.