Talking about closures in js, talking about js closures
First, let's look at a piece of code:
Copy codeThe Code is as follows:
<A href = "javascript: void (0);"> 111 </a>
<A href = "javascript: void (0);"> 222 </a>
<A href = "javacsrept: void (0);"> 333 </a>
Var a = document. getElementsByTagName ("");
Function B (){
For (var I = 0; I <a. length; I ++ ){
A [I]. onclick = function (){
Alert (I );
}
}
}
According to our original design intention, we should click a tag and the serial number of the tag will pop up accordingly, that is, click the first a to bring up 0, click the second to pop up 1... but the fact is that the number of a tags is always displayed. Why? This problem has plagued me for a long time. I have consulted many online materials and reference books, most of which seem to be incorrect. I believe many people do not know much about the reasons, I will talk about my understanding on this issue. If anything is inappropriate, please criticize and correct it.
In my personal understanding, the reason for the failure of the above functions is that the event processing function is bound to variable I, and the event processing function is assigned to onclick, that is to say, this function is called only when the tag is clicked. Therefore, logically, in a simple for loop, function () {alert (I );} this function is not actually executed. When we click the tag, the for loop has already been executed. At this time, the I value is the final state value after the for loop is executed. To put it simply, the I value belongs to the B function, and the I value we need is the value passed into the event processing function in real time. So what method can we achieve our original design intention? A clever person may have guessed it, that is, using closures.
Let's take a look at the code below:
Copy codeThe Code is as follows:
Var a = document. getElementsByTagName ("");
Function B (){
For (var I = 0; I <a. length; I ++ ){
A [I]. onclick = function (j ){
Return function (){
Alert (j );
}
} (I );
}
}
B ();
After executing the above code, we can find that the function we want has been implemented, that is, clicking any a tag will pop up the serial number of the tag. I believe many of my colleagues have read many similar versions of the above Code, but why can we achieve the functions we need by doing so? I am a little bit open-minded, if any, please do not give me any further advice.
The essence of the above Code is the understanding of variable I. In this Code, an immediate call function is found when the function is executed in the for loop. At this time, the real-time I variable value is passed to the immediate call function, and the function is called immediately, the event processing function stores Real-Time I variable values.
The above is all the content of this article. I hope it will be helpful for you to understand js closures.