Two classic uses of closures in javascript
There are a lot of introductions on the Internet. I have read a lot and I am still confused. I will not describe the theory here. I will give two examples directly.
Code 1: record the number of times a function is called
Function a () {var I = 0; function B () {return ++ I;} return B;} var c = a (); c (); // 1c (); // 2
This method is similar to the private static variable in C language. It can keep the memory of local variables from being released.
Code 2: correctly register the event handler for the DOM
<Script type = "text/javascript"> var buttons = document. getElementsByTagName ("input"); for (var I = 0; I <buttons. length; I ++) {// Method 1: The value of I is always 3 // buttons [I]. onclick = function () {// console. log (I + "was clicked. "); //} // Method 2: from 0 to 3, which is the function (I) {buttons [I]. onclick = function () {console. log (I + "was clicked. ") ;}}) (I) ;}</script>