Closures (closure) are a difficult and unique feature of the JavaScript language, and many advanced applications rely on closure implementations. Very early on the concept of closure, but has been confused, not able to figure out what the JavaScript closure is, what is the use, today on the Internet to see an article about JavaScript closures (the original link), Speak very well, This is a thorough understanding of the JavaScript closure is a god horse dongdong and closure of the use of, write here to share with you, I hope that do not understand the JavaScript closure of the friends can understand the closure after reading! Most of the following is from the original text, I added some code comments and operation effect diagram as well as a little modification on the basis of the original text, easy for everyone to understand!
Scope of a variable
To understand closures, you must first understand JavaScript's special variable scope.
In JavaScript, the scope of a variable is divided into two types: global variables and local variables.
In JavaScript, a global variable can be read directly from within a function.
var n=;//defines the global variable n
function f () {
alert ("Access global variable n,n=" +n within a function);//access global variable N} within function
Run Result:
But conversely, you cannot read local variables within a function outside of a function.
function f () {
var n=;//defines a local variable n} alert within the F function
("Accessing the local variable n,n=" +n outside the function);//accessing local variable n outside the function, error: N undefined
Run Result:
Here's a place to be aware that when declaring variables inside a function, you must use the var command. If not, you are actually declaring a global variable!
function f () {
n=;
}
f ();
Run Result:
How to read local variables from the outside?
For a variety of reasons, we sometimes need to get local variables within a function. However, as mentioned earlier, this is not possible under normal circumstances and can only be achieved by workaround.
That is, in the interior of the function, define a function.
function f () {
var n=;//f local variable N
//Inside F function defines an F function functions
f () {
//within F function is an alert that can access local variable n
(n);
}
}
In the above code, the function F2 is included within the function F1, when all local variables within F1 are visible to F2. But the reverse is not, F2 internal variables, the F1 is not visible. This is the "chain scoped" structure (chain scope) peculiar to the JavaScript language, where child objects look up the variables of all the parent objects at one level. Therefore, all the variables of the parent object are visible to the child, and the opposite is not true. Since F2 can read local variables in F1, we can not read the internal variables of F2 as long as the return value of the F1! Maybe someone will have a question, F2 is a function ah, how can be returned as the return value of the F1 function, in fact, it is possible, JavaScript in the function name itself is a variable, so the function can also be used as a normal variable. That is, not only can you pass a function to another function as if you were passing a parameter, but you can return a function as the return value of another function.
function f () {
var n=;//local variable N
//F function function
f () {
alert (n) declared within the F function);
Return
f;//the F function as the return value of the F function
}
var result=f (),//f the returned value after the call is an F function, at which point result is the F function
Run Result:
Third, the concept of closure
The F2 function in the previous section of the code is the closure. The definition of "closure" (closure) in various professional literature is very abstract, such as having a closure definition: "Ajavascript closure is a variable in another scope that holds it from the previous function or scope, These variables are not destroyed with the execution of the upper-level function , and it's hard to understand the closure definition. My understanding is that closures are functions that can read internal variables of other functions. Because in a JavaScript language, only a child function within a function can read a local variable, the closure can be simply understood as "a function defined within a function." So, in essence, closures are a bridge that connects functions inside and outside functions .
Iv. use of closures
closures can be used in many places. Its maximum use is two , one is the previous mentioned can read the function inside the variable, the other is to keep the values of these variables always in memory.
How to understand this sentence? Take a look at the code below.
function f () {
var n=;
Nadd is a global variable that does not use the Var declaration, and this variable now points to an anonymous function declared inside the F function
nadd=function () {n+=} function
f () {
alert (n);
}
return F;
The
var result=f ();//result is the F function result ();
//The first call to the result function
Nadd ();//nadd represents an anonymous function declared inside the F function, Nadd () is to invoke the anonymous function
Run Result:
In this piece of code, result is actually the closure F2 function. It runs two times, the first value is 999, and the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically purged after the F1 call.
Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and the presence of F2 depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call has ended.
Another notable part of this code is the "Nadd=function () {n+=1}" line, which first nadd not use the var keyword, so nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure , so the nadd is equivalent to a setter that can manipulate local variables within the function outside of the function.
Five, use the closure of the attention point
1 because the closure will make the function of the variables are stored in memory, memory consumption is very large, so can not abuse the closure, otherwise it will cause Web page performance problems, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.
2 The closure will change the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, using the closure as its common method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the internal variable of the parent function.
VI. Study Questions
If you can understand the operation results of the following two sections of code, you should understand the operation mechanism of the closure.
Code fragment One:
var name = "The window";
var object = {
name: ' My object ',
getnamefunc:function () {return
function () {
Retu RN THIS.name;
};
}
};
Run Result:
Code fragment Two:
var name = "The window";
var object = {
name: ' My object ',
getnamefunc:function () {
var = this;
return function () {return
that.name;
};
}
};
Run Result:
The following code is annotated to analyze the results of the two code fragments:
Code fragment One:
The analysis is as follows:
/* in JavaScript, our declared JavaScript global objects, global functions, and global variables automatically become members of the Window object.
A global variable is a property of a Window object.
A global function is a method of a Window object. */var name = "the window";//declares a global variable name, at which point the global variable name automatically becomes a property/proof of the Window object: Alert ("Window.name:" +window.name); The name can be accessed in the form of Window.name (object name. Attribute name), which proves that the global variable name automatically becomes an attribute//Declaration object of the Window object. At this point, the global variable object automatically becomes a property of the Window object. var object = {Name: ' My object ',//object object's property name Getnamefunc:function () {//obje The Getnamefunc function of CT object//object The return value of the Getnamefunc method of the object is an anonymous function returning function () {//What object does this refer to at this point, which refers to the Window object,
Which object calls the function where this is, this refers to which object.
The proof of this in the anonymous function is the window object rather than object alert (the result of "This==object is:" + (This==object));
Alert ("This==window's result is:" + (This==window));
Return this.name;//since this represents a Window object, then the nature of the THIS.name access is the Window object's name "the Window"};
}
};
Proof: The Global object is an attribute of the Window object alert ("Window.object:" +window.object);
Alert ("Window.object.name:" +window.object.name); /* After calling the Getnamefunc method, return an anonymous method, at which time RETFN represents the anonymous method, now equivalent to anonymous method to a name called RETFN, at this time the RETFN function automatically became the WIA function of the Ndow object-* var retfn = Object.getnamefunc (); Alert (RETFN ());/Call the returned anonymous method, who is calling this anonymous method? is the Window object//Proof: The RETFN function is a function of the Window object alert ("Window.retfn ():" +WINDOW.RETFN ());//can use WINDOW.RETFN () (object name. Method Name) form to call the Retfn method, it proves that the RETFN function is a function of the Window object
Code fragment Two:
The analysis is as follows:
var name = "the window";//global variable name//Global object = var object = {Name: ' My object ', Getnamefunc:function () {* * this This is what object it represents, this at this point is an object, which object calls this function, this refers to which object executes that = This, then that also represents object/var that = this //that is a local variable declared in the Getnamefunc function//proof that the this in the Getnamefunc function represents an object instead of window alert ("This==object result is:" + (this=
=object));
Alert ("This==window's result is:" + (This==window));
To prove that this represents object alert ("That==object's result is:" + (That==object)); return function () {/*that is a local variable declared in the Getnamefunc function, which normally getnamefunc the local variable will be reclaimed by the JavaScript GC. Frees up the memory space occupied by that local variable, but now that is still in use and not recycled because Getnamefunc is the parent function of this anonymous function, When the Getnamefunc function is called, the anonymous function is returned and assigned to a global variable RETFN, which causes the anonymous function to always be in memory, while the presence of the anonymous function relies on the GETNAMEFUNC function, so the GETNAMEFUNC function is always in memory,
is not reclaimed by the garbage collection mechanism (garbage collection) after the call is completed.
Since the Getnamefunc function is always in memory, that local variable declared inside the Getnamefunc function will always exist in memory, and if so, then of course it can continue to be used.
*/Return That.name;//that represents object objects, then the nature of That.name access is the object's name "My Object"};
} }; var retfn = object.getnamefunc ()//After the Getnamefunc method is called, an anonymous method is returned, at which point Retfn represents the anonymous method, which is now equivalent to giving the anonymous method a name of RETFN alert (RETFN ());
Finally, I'll attach an example that I used to write when I learned about JavaScript closures:
<script type= "Text/javascript" >
function A () {
var i =;//The local variable declared within a function I
//declaration of the inner function of a function B
Function B () {
alert ("i =" + (++i));//within child function b The local variable inside the A function i
}
return b;//Returns the address of this function of B
/
*
After the execution of var C = A (), the variable C actually points to the variable I used in the function b,b,
then executes C () and pops up a window to display the value of I (for the first time), and
This code actually creates a closure,
Because the variable C outside function A refers to function B within function A, that is
, when the internal function B of function A is referenced by a variable outside of function A,
a so-called "closure" closure is created, which
is done after a is executed and returned,
Closures allow JavaScript's garbage collection mechanism GC to not retract the resource occupied by a,
because the execution of the internal function B of a will depend on the variable/
a () in a ();/There is definitely a space for I in memory, and after a () The GC is recycled to the I-allocated memory space.
var c = A ();//This usage, GC does not treat I as garbage disposal
C ();//equivalent to call B (), the result is: i=
C ();//Result: i=
C (); The result: i=
Run Result:
The above content is small series to introduce the JavaScript Knowledge Point Summary (16) JavaScript closure (Closure) code of the relevant content, I hope to help!