This is the shortest article about JS closures.

Source: Internet
Author: User
Function A () {var I = 0;} ();

Each time a executes, a new execution environment is created and the variable I is created in this environment. That is to say, each time I is different. This is called the closure of function a on variable I.

Such CodeIs a typical code without a closure:
For (VAR I = 0; I <9; I ++) {A. childnodes [I]. onclick = function () {alert (I );};}

It has a problem, that is, there is only one variable I, and the final output is the current I (= 9 ). To save the I during execution, use the closure. Make each I different

For (VAR I = 0; I <9; I ++) {var fn = function (m) {var I = m; // use FN to save I. Return function () {alert (I); // we have used the closure to save the variable I};. childnodes [I]. onclick = FN (I );}

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.