Two classic uses of closures in javascript

Source: Internet
Author: User

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>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.