How to look at the nature of closure from JavaScript's cyclic problem

Source: Internet
Author: User
Tags bind closure

The first contact with this problem or when I was just beginning to learn JS, at that time is confused, after more than a year, suddenly reminded of this problem, in this spring-filled weekend, I sat down to study the results and share with you;

First look at the code: demo.html

<! DOCTYPE html>
alert (i);    
          });
  }
()
</script> 
</body> 

Each loop adds a click event to the corresponding numbered paragraph, and the callback function for the event is to execute an alert (); If you haven't used it before, it's also assumed that clicking a paragraph pops up the corresponding number in the paragraph 0,1,2,3,4. But actually are all pop 5;

There are already a lot of discussion blogs on the internet, and they give a lot of ways to pop up the corresponding numbers. The easier way to understand this is as follows:

1, the variable i is saved on a property of the corresponding paragraph:

~function Test () {   
    for (var i=0; i<5; i++) { 
         $ (' #p ' +i). bind ("click", Function () {
             alert ($ (this). attr (" Index "))    
          . attr ("index", I);
  };
} ();

2, add a layer closure, I pass the function parameter form to the inner layer function:

~function Test () {   
    for (var i=0; i<5; i++) { 
         (function (param) {
             $ ("#p" +i). Bind ("click", Function () {
  alert (param);  
          })
         (i);
            
  };
()

There are other ways, of course, but it's not very well understood.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

And what I'm going to explore is why the return value in Demo.html is always 5. The online argument is that "variable i is stored in a function as a pointer or a variable address," because it can only be explained in this way. But only by virtue of a conclusion how to serve the public?

When it comes to pointers or variable addresses, it's a commonplace in C, but in a sexy language like JS, it's rarely used except for objects and their object attributes. A basic data type is actually linked to the pointer, which brings up the desire to explore.

3, try the following code

~function Test () {   
    var temp =10;
    for (var i=0 i<5; i++) { 
        $ ("#p" +i). Bind ("click", Function () {
                alert (temp);    
         });
    temp=20;
} ();

The result of this is that each paragraph is ejected in 20, not 10. Indicates that the temp value is already 20 when we click at that time. This is an obvious result that doesn't seem to be needed, because the temp has been assigned to 20 before we click.
4, and then look at the code below, we have the program to trigger the Click event before the temp is changed, and the popup is 10;

~function Test () {   
    var temp =10;
    for (var i=0 i<5; i++) { 
        $ ("#p" +i). Bind ("click", Function () {
                alert (temp);    
         });
         if (i===1) {
          $ ("#p0"). Trigger ("click");
    temp=20;
} ();

This means that the Click event callback function of the binding $ ("#p0") was supposed to return 10, and when I manually clicked the P0 paragraph again, the reason for the pop-up 20 was because the temp value changed. It also means that each time you pop up, you are accessing the temp value at the moment, not the value of the binding, which means that the variable temp is actually saved as a variable address. The extension is that the function internally accesses a variable of the same sibling as the function, and the variable is resident memory. Accessing the variable is essentially accessing the variable's address;

With the above conclusions, we can simply describe the nature of closures: A variable that is obtained in the parent scope is saved in the child scope, and these variables are not destroyed as the parent scope is destroyed because they already reside in memory!

This statement also explains the closure features: 1: Because the resident memory will cause memory leaks 2, as long as other scopes can be taken to the child scope of the provider, then the other scope has a way to access the scope of the child scope of the domain variables.

See examples of such a typical closure:

function A () {
   var a=1;
        
    function B () {return
        A;
   };
       
    return  B;
};
    
    
var  c=a ();//c obtains the provider
Console.log (C ()) of A's child scope B;//1    C can access the variable A in the parent scope of B

Author: cnblogs Wimber

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.