A brief discussion of closures in js

  • 2020-05-16 06:19:19
  • OfStack

First let's look at a piece of code:


<a href="javascript:void(0);">111</a>
<a href="javascript:void(0);">222</a>
<a href="javacsript:void(0);">333</a>
var a=document.getElementsByTagName("a");
  function b(){
    for(var i=0;i<a.length;i++){
    a[i].onclick=function(){
      alert(i);
    }  
  }
}

According to the original intention of our design, it should be that clicking on an a tag will pop up the serial number of the tag accordingly, that is, clicking on the first a will pop up 0, and clicking on the second will pop up 1... But the fact is that the number of a tags that pop up all the time, why is that? This problem puzzled me for a long time, looked up a lot of online information and reference books, most of what said is specious, I believe that there are many students do not understand the reasons, on this issue I talk about my own understanding, if there is inappropriate, please correct criticism.

As far as I can see, the reason why the above function fails to achieve its purpose is that the event handler binds to the variable i, which in turn assigns a value to onclick. This means that the function is only called when the a tag is clicked, so logically, in the pure for loop, function(){alert(i); } this function is not actually executed, but when we click the a label, the for loop has already been executed, at this time, the i value is the final state value of the for loop. In simple terms, the value of i belongs to the b function, while the value of i we need is the value passed into the event handler function in real time. So what are some ways that we can do this? As the smart ones might have guessed, use closures.

Let's look at one more piece of code:


var a=document.getElementsByTagName("a");
  function b(){
    for(var i=0;i<a.length;i++){
      a[i].onclick=function(j){
        return function(){
        alert(j);
      }
    }(i);
  }
}
b();

By executing the above code, we can find that the desired function has been realized, that is, clicking any a label will bring up the serial number where the label is located. For the above code, I believe that many students have seen many of the same version, but why do so can achieve the function we need to do, 1 is a personal 1 point of shallow, if there is not appropriate, please grant me.

An understanding of the above code is essentially an understanding of the variable i. In this code, when the function executes into the for loop, it finds an immediate call to the function. At this time, the real-time i variable value is passed to the immediate call function. The function is immediately called, and the event handler also stores the real-time i variable value.

That's all for this article, and I hope it will help you understand the js closure.


Related articles: