A brief analysis of JavaScript closure (Closure) usage examples _javascript skills

Source: Internet
Author: User
Tags anonymous closure garbage collection

The examples in this article describe JavaScript closures (Closure) usage. Share to everyone for your reference, specific as follows:

Closure is translated into "closure", feeling that it is too scholarly to be packaged. The following bibliography and online resources are briefly discussed (please note the improper understanding).

1, what is closure

The official answer: The term "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.

Read the above definition, if you are not a master, I firmly believe that you will be as angry as I questioned: This TMD is a words?
To understand the closure, or the code is the most persuasive ah, on the code:

 Innerfunctest (
 {
    alert (tmpnum);//reference temporary variable of outer function Functest Tmpnum
 }
 return innerfunctest;//back to internal function
}
Call function
var myfunctest=functest (); 
Myfunctest ()//Eject 100

In the code above, the annotation has been written clearly. Now we can understand the "closure": the function body defines another function as the target object's method function (in the example is to define another function in the function Functest Innerfunctest as the Functest method function), This object's method function, in turn, refers to the temporary variable in the outer function body (the closure is a mechanism for indirectly preserving the variable value). In the example is the internal function innerfunctest the temporary variable tmpnum referencing the outer function functest, it must be noted that the temporary variable can include all the local variables, arguments, and other internal functions declared in the external function. When one of these intrinsic functions is called outside the external function containing them, a closure is formed (in the example, when the function is called, the myfunctest actually calls the Innerfunctest function, That is to say, an internal function of functest is called outside of Functest, and a closure is created. Innerfunctest

2, two examples of using closures

Here are two examples, one is because the closure causes the problem, and the other uses the closure to skillfully pass the function's scope binding parameters.

These two examples of related HTML tag pieces are as follows:

<a href= "#" id= "closureTest0" > Take advantage of closures (see prompts after 1 seconds) </a><br/> <a href= "
#" id= "ClosureTest1" > Examples of problems caused by closures 1</a><br/>
<a href= "#" id= "ClosureTest2" > The example of a problem caused by closures 2</a><br
<a href= "#" id= "ClosureTest3" > Examples of problems caused by closures 3</a><br

(1), due to closures and cause problems

There are 4 <a> elements in the HTML tag snippet above, and now give the latter three specified event handlers so they can report their own order on the page when the user clicks, such as: When the user clicks the 2nd link, it reports "you clicked the 1th link." To do this, if you write a function that lists the following three links to add an event handler:

function Badclosureexample () {for
  (var i = 1; I <4; i++) {
    var element = document.getElementById (' closuretest ') + i);
    element. onclick = function () {
      alert (' You clicked the first ' + i + ' link ');}}


Then, call the function after the page load completes (or it might be an error):

Window.onload = function () {
  badclosureexample ();
}

Looking at the results of the run, click on the back 3 links to see what information is displayed in the warning box? --It's all "the 4th link you clicked." Did it make you feel so surprised? Why?

Analysis: Because the event handler assigned to Element.onclick in the Badclosureexample () function, that is, the onclick anonymous function is in Badclosureexample () The function is called when the user clicks the link when it finishes running. When called, you need to evaluate the variable I, and the parser first looks inside the event handler, but I don't define it. Then, looking in the Badclosureexample () function, there is a definition, but the value of I is 4 (only I greater than 4 stops executing the FOR loop). Therefore, the value is obtained-this is exactly the result of the closure (anonymous function) to use the variable in its outer function (Badclosureexample) scope. Also, this is caused by the inability of the anonymous function itself to pass arguments (and therefore cannot maintain its own scope).

So how does this example solve the problem? In fact there are a lot of ways (I might as well write a look), I think more simple direct code:

function Popnum (onum) {return
  function () {
          alert (' You clicked on ' +onum+ ' link ');
  }
function Badclosureexample () {for
  (var i = 1; I <4; i++) {
    var element = document.getElementById (' closuretest ') + i);
    element. onclick =new Popnum (i);
    }
}

(2), skillfully using closure binding parameters

or the above HTML fragment, we want to when the user clicks the first link time delay pop-up a warning box, how to achieve? The answer is to use the settimeout () function, which calls a function after the specified number of milliseconds, such as:

Copy Code code as follows:
SetTimeout (somefunc,1000);

The problem is that you cannot pass arguments to the SomeFunc function. With closures, you can easily solve this problem:

function Goodclosureexample (omsg) {return
  function () {
    alert (omsg);}
  ;
}

function goodclosureexample is used to return an anonymous function (closure). And we can bind the returned anonymous function to this parameter by passing arguments to it, such as:

Copy Code code as follows:
var good = goodclosureexample (' This parameter is bound by a closure ');

At this point, the good function that is bound to the parameter can be passed to the settimeout () to implement the delay warning:
Copy Code code as follows:
settimeout (good,1000)//The parameter is already bound at this time good

Finally, test the complete code through:

Window.onload = function () {
  var element = document.getElementById (' closureTest0 ');
  if (element) {
    var good = goodclosureexample (' This parameter is bound by a closure ');
    Element.onclick = function () {
      settimeout (good, 1000);//delay 1 seconds pop-up prompt
    }
  }


3, JavaScript garbage collection principle

(1), in JavaScript, if an object is no longer referenced, then the object will be collected by GC;

(2) If two objects are referenced to each other and are no longer referenced by the 3rd, then the two referenced objects are also reclaimed.

Using closures in JS often creates problems for JavaScript's garbage collector. Especially when encountering complex circular references between objects, the logic of garbage collection is very complicated, so it is dangerous to leak the memory, so it is prudent to use closure. Ms does not seem to recommend using closures.

I hope this article will help you with JavaScript programming.

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.