Closure Analysis of javascript Learning

Source: Internet
Author: User

In ECMAScript, all declared variables seen outside the function at the function declaration can be accessed inside the function.Final value!

Closure functions can only access the final value of a variable !!!

Eg:

Function fnTest (arr ){
For (var I = 0; I <arr. length; I ++ ){
Arr [I] = function () {alert (I + "|" + arr [I]);};
}
}
Var arr = [0, 1, 2, 3];
FnTest (arr );
For (var I = 0; I <arr. length; I ++ ){
Arr [I] (); // always output 4 and an undefinedBecause the I value is 4 after the function exits, the accessed value is only 4

// The result is continuous.Four "4 | undefined" are displayed"
}

 Not only can the variable values outside the closure be accessed in the closure, but also its values can be set.

Eg:

Function fnTest (){
Var a = "June ";
Return {
Set: function (param ){A = param},
Get: function () {return}
};
}
Var obj = fnTest ();
Alert (obj. get ());//June is displayed.

Obj. set (586 );
Alert (obj. get ());//586 

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.