JavaScript Learning Notes (iii)--closures

Source: Internet
Author: User

1. What is a closure?

Features of closures:

    • function nesting functions (intrinsic functions, external functions)
    • Intrinsic functions can refer to arguments or variables of an external function
    • parameters or variables of external functions will not be retrieved by JS garbage collection mechanism

function aaa () {

var a = 1;

function bbb () {

alert (a);

}

return BBB;

}

var c = aaa ();

C ();

-= = Expression form

(function () {

var a = 1;

return function () {

alert (a);

}

})();

2. What are the benefits of closures?

    • Expect a parameter or variable to be stationed in memory for a long time (it will not be reclaimed by the garbage collection mechanism of the external function)
    • Avoid contamination of global variables
    • Implementing the existence of a private member

  

function aaa () {

var a = 1;

a++;

alert (a);

}

AAA (); 2

AAA (); 2, each call to AAA (), a value starting from 1, if you want to call AAA () to achieve a worth of accumulation, how to do? --Closed Bag

=>function aaa () {

var a=1;

function bbb () {

a++;

alert (a);

}

return BBB;

}

var c= aaa ();

C (); 2

C (); 3

C (); 4 since AAA () is executed, variable A is not reclaimed by the garbage collection mechanism, but is stationed in memory, so each time the BBB () is executed, a value is added 1 on the memory worth

3. What is the use of closures?

    • Code of the module will, the privatization of members

  

var c= (function () {

var a=1;

function aaa () {

a++;

alert (a);

}

function bbb () {

a++;

alert (a);

}

return {

AA:AAA,

bb:bbb

}

})();

C.aa (); 2

C.BB (); 3

alert (a); Error, because a privatized member

Alert (AAA ()); Error

4. Closures are prone to memory leaks under IE

5. The core of closures is the use of parameters and variables that are not recycled by the JS garbage collection mechanism.

JavaScript Learning Notes (iii)--closures

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.