Javascript closure Formation

Source: Internet
Author: User
Tags closure definition
// Example 1 var A = 10086; function F1 () {alert (a) ;}f1 (); // 999 // Example 2: when the internal variable of the function is declared, you must use var. Otherwise, a global variable function F2 () {var B = 10086;} F2 (); alert (B); // errer: B is defined // Example 3: for example, C is the global variable function F3 () {c = 10086;} F3 (); alert (C ); //// ======================================/// Example 2 we need to access B's what should I do when the value is set? // all the variables in F4 are visible to getd, however, the variables in getd are invisible to F4. in this way, our F4. // Example 4 function F4 () {var d = 10000; function getd () {alert (d);} return getd () ;}// closure definition: it can be simply understood as the purpose of the function defined inside the function // closure: Read the internal variables of the function and keep the value of the variable in the memory // Example 5 function F5 () {var n = 100086; add = function () {n + = 1}; function getn () {alert (n) ;}return getn ;} // In this case, no closure will occur when calling F5 (); // output 10086 add (); F5 (); // 10086 // use the fun variable, form the closure var fun = F5 (); // use fun to point to getn fun (); add (); fun (); // when var fun = F5 () is executed, variable fun actually points to the function getn, and getn uses the Variable N // when the function getn inside function F5 is referenced by function a's external variable, A closure // closure is created: After a is executed, it returns the result. The closure is not recycled because the Variable N is referenced externally, so n always exists, if we do not return getn, the value of N will not be called and will be recycled.

 

References

Uncover the true face of JavaScript closures

Learning JavaScript closures (closure)

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.