The concept and application of JS closure are not mentioned here. It is only a simple test for personal understanding. If the answer is correct and you know what is going on, it means you have almost mastered the principle of closure.
Read the question:
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<SCRIPT type = "text/JavaScript">
Function F1 (){
VaR arr = Document. getelementsbytagname ("p ");
For (VAR I = 0; I <arr. length; I ++ ){
Arr [I]. onclick = function () {alert (I );}
}
}
</SCRIPT>
</Head>
<Body onload = "F1 ();">
<P> click I 0 </P>
<P> click I 1 </P>
<P> click I 2 </P>
<P> click 3 </P>
</Body>
</Html>
Try to answer what value will pop up when the above Code is clicked?
If it is 0, 1 ...... Then it is wrong (at first I also got wrong ^_^)
The correct answer is 4.
Why? Search for the JS variable scope on the Internet and you will understand it (but I still cannot understand it ......)
Solution
In fact, there are several solutions, such as hiding the domain. What I want to talk about is the closure method.
Please refer to the code
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<SCRIPT type = "text/JavaScript">
Function F1 (){
VaR arr = Document. getelementsbytagname ("p ");
For (VAR I = 0; I <arr. length; I ++ ){
Arr [I]. onclick = (function (k) {return function () {alert (k) ;}}) (I); // This has changed
}
}
</SCRIPT>
</Head>
<Body onload = "F1 ();">
<P> click I 0 </P>
<P> click I 1 </P>
<P> click I 2 </P>
<P> click 3 </P>
</Body>
</Html>
Run the code. Sure enough.
Google understands why.
There is another ......
This example shows others, but it is typical to use ^
He used this keyword carefully.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<script type="text/javascript">
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()());
</script>
</HEAD>
<body >
</body>
</HTML>
Guess what the result is?
Answer: "The Window"
If you can understand the above two examples, you can try the closure application. Haha ......