# Closed Bag #
My understanding: In the interview, first say the scope chain, and then the cause of the closure, then garbage collection GC, finally said closures.
A. A variable declared inside a function is its private variable.
B. In JavaScript attributes, a function is a variable that can access all the variables in its scope chain.
C. But outside the function, private variables cannot be accessed directly inside the function.
D. The child function returns a variable of the parent function by nesting the function inside the function, creating a closure.
Presentation of closures
The essence of modularity is to create local contexts to hold local variables by local scope properties of functions
1. function as return value
function fn () {
var count = 0;
return function () {//This sentence is the key
count++;
Console.log (count)
}
}
var a = fn ()
A (); 1
A (); 2
A (); 3
A (); 4//a as a variable, is a reference to the FN (), so FN has not been released
A = FN ()//re-assigns a value to a, re-references the FN to a so that the middle is released
A (); 1
2. function as parameter Pass
var max = 10;
VAR fn =function (x) {
if (X>max) {
Console.log (x)
}
}//max is a free variable that is fixed after FN is defined, so Max =10
function fn1 (f) {
var max = 100;
f (15);
}
FN1 (FN)//15
3. Information exposure and concealment
function fn () {
var a = 10;
var b = [1,2,3,4];
var count = 0;
function Addcount () {
count++
};
function GetCount () {
return count;
}
return {
Add:addcount,
Get:getcount
}
The objects exposed here are only two methods, while private variables A and B are not exposed, so they are confidential and can be selectively exposed ———— modular SEAJS is the way to achieve
}
var a = fn (); Will refer to a
4. Asynchronous callbacks
Closures--Asynchronous callbacks
function fn () {
var i = 0;
Window.setinterval (function () {
Console.log (i++)
},1000);
Console.log (' Prevent ')
}
FN ()
Note: setinterval () is typically asynchronous, fn prints out ' prevent ' after execution, and the FN call should be destroyed, but the timer is still executing, so FN is still there.
Closure-javascript Object-oriented advanced