JS closure ~ You do not understand ~ I pretend to understand it ~

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:

1 Function Functest ()
2 {
3 VaR Tmpnum = 100 ; // Private variable
4
5 // Define another function in the function functest as the functest method function.
6 Function Innerfunctest (
7 {
8 Alert (tmpnum ); // Reference the Temporary Variable tmpnum of the outer function functest
9 }
10
11 Return Innerfunctest; // Returns an internal function.
12 }
13
14 // Call a function
15 VaR Myfunctest = Functest ();
16 Myfunctest (); // 100
17

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 includeAllLocal 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 ).

Javascript variable scopes are maintained through functions. For example, for a function:

1 Function Add (a, B ){
2 Return A + B;
3 }

When using different parameters (functions without parameters are the same) to call it:

1 VaR Sum1 = Add ( 1 , 2 );
2 VaR Sum2 = Add ( 3 , 4 );

Each call maintains a new function scope by creating a new call object, which ensures that sum1 and sum2 obtain the corresponding values 3 and 7 respectively.

The principle of closure is also true. 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:

1 < A Href = "#" ID = "Closureexample" > Example of using closure (you will see the prompt in 0.5 seconds) </ A >
2 < A Href = "#" ID = "Closureexample2 ″ > Example 1 caused by closure </ A >
3 < A Href = "#" ID = "Closureexample3 ″ > Example 2 of problems caused by closures </ A >
4 < A Href = "#" ID = "Closureexample4 ″ > Example 3 of problems caused by closures </ A >

Example 1: Problems caused by closures

There are four <A> elements in the area tag fragment. Assume that you want to process the last three specified events.ProgramTo report the order of users on the page when they click. For example, when a user clicks 2nd links, the report "you clicked 2nd links" is reported ".

To this end, if you write the following functions for adding Event Handlers for the last three links:

1 Function Badexample (){
2 For ( VaR I =   2 ; I <=   4 ; I ++ ){
3 VaR El = Document. getelementbyid ( ' Closureexample '   + I );
4 El. onclick =   Function (){
5 Alert ( ' The '   + I +   ' Links ' );
6 }
7 }
8 }

Then, call this function after loading the page (or an error may be reported:

1 Window. onload =   Function (){
2 Badexample ();
3 }

Click the last three links. What information is displayed in the warning box? -- All of them are "5th links you clicked ". Why?

Because El. onclick event handler-that is, the anonymous function is called after the badexample () function is run (when the user clicks the link. During the call, the variable I needs to be evaluated. The parser will first find the variable in the event handler, but it is not defined. Then, go to the external scope, that is, find in the badexample () function. It is defined at this time, but the value of I is 5 (The for loop will be stopped only when I is greater than 5 ). Therefore, the value will be obtained-this is the result of the variable in the scope of the closure (anonymous function) to use its external function (badexample. In addition, this is because anonymous functions cannot pass parameters (so they cannot maintain their own scopes. How can we solve this problem ?. Reference answer:

1 Function Badexample (){
2 For ( VaR I =   2 ; I <=   4 ; I ++ ){
3 VaR El = Document. getelementbyid ( ' Closureexample '   + I );
4 El. onclick =   New Popnum (I );
5 }
6 }
7 Function Popnum (onum ){
8 Return   Function (){
9 Alert ( ' The ' + Onum + ' Links ' );
10 }
11 }

Example 2: Use closures to bind Parameters

Or the above HTML snippet, We will pop up a warning box when the user clicks the first link-pay attention to latency-how to implement it? The answer is to use the setTimeout () function, which calls a function after the specified number of milliseconds, such:

1 SetTimeout (somefunc, 500 );

However, the problem is that the parameter cannot be passed to the somefunc function. The closure can easily solve this problem:

1 Function Goodexample (I ){
2 Return   Function (){
3 Alert (I );
4 };
5 }

The goodexample 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:

1 VaR Good = Goodexample ( ' This parameter is bound through the closure. ' );

In this case, the good function bound to the parameter can be passed to setTimeout () for latency warning:

1 SetTimeout (good, 500 ) // At this time, a parameter has been bound to good.

Finally, combined with specifying an event handler for the first link, the complete code is:

1 Window. onload =   Function (){
2 VaR El = Document. getelementbyid ( ' Closureexample ' );
3 If (EL ){
4 VaR Good = Goodexample ( ' This parameter is bound by the closure. ' );
5 El. onclick =   Function (){
6 SetTimeout (good, 500 );
7 }
8 }
9 }

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.