Javascript Closure (Closure) usage example _ javascript skills

Source: Internet
Author: User
This article mainly introduces the usage of javascript Closure (Closure), and analyzes the concept, functions, and usage skills of JavaScript Closure in detail based on the instance form. It has some reference value, for more information about how to use javascript closures, see the example in this article. We will share this with you for your reference. The details are as follows:

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 is a closure?

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, the Code is the most convincing. On the Code:

Function funcTest () {var tmpNum = 100; // Private variable // define another function in the function funcTest as the funcTest method function innerFuncTest ({alert (tmpNum ); // reference the Temporary Variable tmpNum} return innerFuncTest of the outer function funcTest; // return the internal function} // call the function var myFuncTest = funcTest (); myFuncTest (); // The 100 message is displayed.

In the above Code, the annotations have been clearly written. Now we can understand the "closure" as follows ": define another function as the method function of the target object in the function body (in the example, define another function innerFuncTest as the method function of funcTest in the function funcTest ), the method function of this object references the temporary variables in the outer function body (closure is a mechanism that indirectly maintains the value of the variable. The internal function innerFuncTest references the Temporary Variable tmpNum of the outer function funcTest, temporary variables can include all local variables, parameters, and other declared internal functions declared in external functions ). When one of these internal functions is called outside 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 to say, 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:

Example of using closure (a prompt will be displayed in 1 second)
Example 1 caused by closure
Example 2 of problems caused by closures
Example 3 of problems caused by closures

(1) problems caused by closures

The preceding HTML Tag contains four elements. Now you need to specify the Event Handlers for the last three so that they can report their order on the page when the user clicks. 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:

Function badClosureExample () {for (var I = 1; I <4; I ++) {var element = document. getElementById ('closuretest' + I); element. onclick = function () {alert ('the link you clicked is '+ I + ');}}}

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:

Function popNum (oNum) {return function () {alert ('the link you clicked '+ oNum +');} 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. A warning box is displayed when the user clicks the first link. 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:

The Code is as follows:

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:

The Code is as follows:

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:

The Code is as follows:

SetTimeout (good, 1000) // The parameter has been bound to good.


Finally, the complete code passed the test:

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); // a prompt is displayed after a delay of 1 second }}}

3. Principles of javascript Garbage Collection

(1) In javascript, if an object is no longer referenced, the object will be recycled by GC;

(2) If two objects reference each other and are no longer referenced by 3rd, the two objects will be recycled.

Using closures in javascript often makes it difficult 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.

I hope this article will help you design JavaScript programs.

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.