An example of js Closure

Source: Internet
Author: User

Copy codeThe Code is as follows:
Function outside ()
{
Var myVar = 1;
Return function (){
Alert (myVar );
}
}
Var t = outside ();
T ();

The internal function of a function in js can still access the variables defined in this function after the function is executed. This is called Closure)
The following example adds an onclick event to three anchor1, anchor2, and anchor3. The expected effect is that the corresponding anchor4 is displayed when you click the anchor3 ", this is the logic bug caused by the closure. After the function of the add event is executed, the I value is 4,
Copy codeThe Code is as follows:
ADS. addEvent (window, 'load', function (W3CEvent) {m
For (var I = 1; I <= 3; I ++ ){

Var anchor = document. getElementById ('anchor' + I );

ADS. addEvent (anchor, 'click', function (){
Alert ('My id is anchor '+ I );
});
}
});

Related Article

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.