What is the process of stack zone and pre-execution for resources not released? The following is a common example:
For example, we now have a ul, and there are a lot of li below. We need to traverse them and bind them with click events, and then pass the current subscript to another function for additional processing:
Copy codeThe Code is as follows:
For (var I = 0; I <agroup. length; I ++ ){
Agroup [I]. onclick = function (){
Handler (I );
}
}
The execution result is obvious, right? In handler, get the passed parameter I, and all you see will be the largest subscript. At this time, we usually use the following solution:
Copy codeThe Code is as follows:
For (var I = 0; I <agroup. length; I ++ ){
Agroup [I]. I = I
Agroup [I]. onclick = function (){
Handler (this. I );
}
}
Here, let's talk about the point of this. In general, this in javascript points to the object Currently referencing it. We have added an I attribute for this. Its value is the current lower value.
So how can we solve this problem using closures? In fact, the principle is the same. We need to save the I value in advance, or it is called transfer:
Copy codeThe Code is as follows:
For (var I = 0; I <agroup. length; I ++ ){
Agroup [I]. onclick = function (index ){
Return function (){
Handler (index );
}
} (I );
}
At this time, you will get the correct subscript. What are the similarities between this and adding the I attribute? That is, they all pass or store the subscript I value in advance. In the preceding demo, The onclick function is pre-executed.
An embedded function is returned in the function to form a stack zone without resources being released, and the I value is passed into the scope as a parameter during pre-execution (there is a problem with the interpretation capability, I don't know if this sentence is correct. You are welcome to use the tile ).
To sum up, the function of a closure is usually to change the scope or pre-execution. It should be noted that the example above is very limited, and the application scope of closure is very wide. Only by understanding its cause and effect can we use it flexibly.
Auntion 2011-11-15
Mail Auntion@gmail.com
QQ 1, 82874972
For Original Articles, please respect the hard work of typing and the rights and interests of the author. Do not delete the author information here during reprinting.