I used to read the plusionaljavascript section of zakas and the closure section. I thought I understood it theoretically and I used all the cases in the book. However, the example is purely implemented through console debugging and is not impressive. When practicing native javascript today, we will encounter closures and simply sort them out... SyntaxHighlighter. all
I used to read zakas's Professional JavaScript and the section on closures. I thought I understood it theoretically and I used all the cases in the book. However, the example is purely implemented through console debugging and is not impressive. Today, when practicing native javascript, we encounter closures and simply sort them out.
First look at the DEMO of the instance:
Http://cssplusplus.com/demo/js/1_1_DivControl%20.html
Implementation Code:
01
02
03
04
19 script
20 function changeStyle (elem, attr, value ){
21 elem. style [attr] = value;
22}
23 window. onload = function (){
24 var Attr = ["width", "height", "background", "display", "display"];
25 var Val = ["200px", "200px", "red", "none", "block"];
26 var oBtn = document. getElementsByTagName ("input ");
27 var oDiv = document. getElementById ("changBox ");
28
29 for (I = 0; I <oBtn. length; I ++ ){
30 oBtn [I]. index = I;
31 oBtn [I]. onclick = function (){
32 (this. index = oBtn. length-1) & (oDiv.style.css Text = "");
33 changeStyle (oDiv, Attr [this. index], Val [this. index]);
34}
35}
36 };
37 script
38
39
40
41
42
43
44
45
46
47
48
49
If we take the 33 rows:
1 changeStyle (oDiv, Attr [this. index], Val [this. index]);
Changed:
1 changeStyle (oDiv, Attr [I], Val [I]); www.2cto.com
What are the results?
This is the modified DEMO:
Http://cssplusplus.com/demo/js/1_1_DivControlWrong.html
Clicking the button above does not respond.
The problem occurs on the closure. The problem analysis is as follows:
1. I bound a function to the onclick action of each button.
2. When I click the button, this function will be called.
3. Execute this function to changeSytle and start searching for parameters.
4. What is the variable I in the parameter?
5. First, find I from the scope of the current anonymous function.
6. Go to the anonymous function bound to window. onload (note that there is no block-level scope concept in javascript) and find
7. What is I? I = oBtn. length, because after the anonymous function bound to window. onload returns, the value of variable I is oBtn. length.
8. This is exactly the I reference value saved in the scope chain of the anonymous function bound to onclick.
Author: Li yuhao