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