1. Scope of variables: Global variables, local variables
- Local variables can be read directly inside the function
JS Code
var n=2;
function Fun () {
alert (n);
}
Fun (); 2
- Cannot read function internal local variables outside function
JS Code
function Fun () {
var n=2; Note that the Var is used here, otherwise the global variable is declared
}
alert (n); Error
- The following n is declared as a global variable
JS Code
function Fun () {
n=2;}
alert (n); 2
2. How can I read local variables from outside?
Sometimes it is necessary to get local local variables inside the function, which can not be done under normal circumstances, only the flexibility is possible. Define a function inside the function
JS Code
function Fun () {
var n=2;
function F2 () {
alert (n); 2
}
}
The above code, theF2 function is contained in the fun function, when the local variables inside the fun F2 is visible, and F2 internal variables, the fun not visible, this is the JavaScript"chain-scoped" structure
The child object looks up the variables of all the parent objects first-level, that is, all the variables of the parent object are visible to the child object, and vice versa.
JS Code
function Fun () {
var n=2;
function F2 () {
alert (n);
}
return F2;
}
var result=fun ();
Result (); 2
3. Closure concept
The F2 function above is the closure.
A simple understanding of closures is the ability to read functions inside variables of other functions, bridging the function's interior to the outside of the function
4. Use of closures
In fact, many things can be done by using closures. For example: Simulation of object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution
Note: According to the above knowledge, all variables without the keyword, the default is added to the global object's properties, temporary variables added to the global variable there are many disadvantages, such as: Other functions may misuse these variables, causing the global object is too large, affecting access speed (because the value of the variable needs to traverse from the prototype chain) .
4.1 anonymous child execution function
Some functions only need to be executed once and their internal variables are maintained in a disorderly order, such as UI initialization, we can use closures
JS Code
var datamodel={ table:[]; Tree:[];} (function (DM) {for (var i=0;i<DM. table.rows;i++) { var row=dm.table.rows [i]; For (Var j=0;j<row.cells;i++) { Drawcell (i,j); } } Build Dm.tree}) (Datamodel);
Create an anonymous function and execute it immediately, since the external cannot reference its internal variables, so it will be released shortly after execution, and most of all, this mechanism will not pollute global variables
4.2 Cache
If we are dealing with a time-consuming function object, each call will take a long time, then we need to store the computed value, when the function is called, first in the cache to find, if not found, then calculate, then update the cache and return the value, if found, directly return the lookup value.
Closures are the only thing that can do this because it does not release external references, and the values inside the function can be preserved. reduce global variables, resident memory, can implement cache
JS Code
Function F1 () { var n=99; Nadd=function () { n+=1; } function F2 () { alert (n); } return F2; } var result=f1 (); Result ();//99 Nadd (); Result ();//100
Why is the local variable n in F1 kept in memory and not automatically cleared after the F1 call ends?
F1 is the parent function of F2, F2 is assigned to a global variable, causing F2 to always be in memory, while F2 's presence is dependent on F1, so F1 is always in memory and will not be reclaimed by garbage collection mechanism after the call ends.
4.3 implementation Encapsulation
4.3.1 The following example, it is not possible to access its internal variables outside of person, by providing a closure to access
JS Code
var person=function () { var name= "Jack"; return{ getname:function () { return name; }, setname:function (newName) { name=newname; } } } (); alert (person.name); Direct access results are: undefined alert (person.getname ()); Jack person.setname ("Lihua"); Alert (Person.getname ());
4.3.2
Closures Another important use is to implement object-oriented objects, the traditional language provides a template mechanism for the class, so that different objects (instances of the class) have independent Members and state, non-interference. Although there is no such mechanism in JavaScript, it is possible to simulate such a mechanism by using closures.
JS Code
function person () { var name= "Jack"; return{ getname:function () { return name; }, setname:function (newName) { name=newname; } } }; var Jone=person (); Alert (Jone.getname ()); Jack jone.setname ("Lihua"); Alert (Jone.getname ()); Lihua var miss=person (); Alert (Miss.getname ()); Miss.setname ("Wanghai"); Alert (Miss.getname ());
The above code Jone and miss can become instances of the person class, because these two instances have independent, complementary effects on the access of this member of name.
5 using closures should pay attention to the problem
5.1 Memory leaks
Closures will make the variables in the function in memory, memory consumption, it can not abuse closures, otherwise resulting in Web page performance problems (slow browser response, reduce user experience and even cause the browser unresponsive, etc.), in IE may cause memory leaks
5.2 Contextual Applications
jQuery Code
$ (function () {
var con=$ ("Div#panel");
this.id= "Content";
Con.click (function () {
alert (this.id); Panel
});
});
this.id Displays the assigned content, and in the click Callback, the resulting closure is referenced to this.id, but the alert pops up "Panel", Cause: Although a closure can refer to a local variable, this is referred to here because the invocation object exists so that when the closure is called (when this Panel's Click event occurs), the This reference is con this jQuery object, and the anonymous function this.id= "Content" is the operation of the anonymous function itself.
If you want to handle the value accessed in the function in the event, you must make some changes
$ (function () {
var con=$ ("Div#panel");
this.id= "Content";
var self=this;
Con.click (function () {
Alert (self.id); Content
});
});
A preliminary study of JS closure package