1, what is the closure of the package
Closures, the official explanation for closures is that an expression (usually a function) with many variables and environments that bind these variables is also part of the expression. Features of closures:
1. As a reference to a function variable, when the function returns, it is in the active state.
2. A closure is when a function returns, a stack that does not release resources.
To put it simply, JavaScript allows the use of intrinsic functions-that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed.
2, the closure of several ways of writing and usage
The first thing to understand is that in JS everything is an object, and a function is a kind of object. Let's take a look at the 5 types of closures, and simply understand what closures are. It will be explained in detail later.
// The 1th kind of notation function Circle (r) { this. R = r; } = 3.14159; function () { returnthis. R; } var New Circle (1.0); Alert (C.area ());
There is nothing special about this notation, just adding some attributes to the function.
//The 2nd kind of notationvarCircle =function() { varobj =NewObject (); Obj. PI= 3.14159; Obj.area=function(r) {return This. PI * R *R; } returnobj; } varc =NewCircle (); Alert (C.area (1.0));
The notation is to declare a variable and assign a function as a value to the variable.
// The 3rd kind of notation var New Object (); = 3.14159; function (r) { returnthis. PI * R * r; } 1.0));
This method is best understood, that is, the new object, and then add properties and methods to the object.
// The 4th kind of notation var circle={ "PI": 3.14159, "area":function(r) { return this. PI * R * r; } ; Alert (Circle.area (1.0));
This method is used more and is most convenient. var obj = {} is the declaration of an empty object.
// The 5th kind of notation var New Function ("this. PI = 3.14159;this.area = function (r) {return r*r*this. PI;} " ); Alert ((new Circle ()). Area (1.0));
To tell the truth, this kind of writing I did not use, we can refer to.
In general, the above several methods, 2nd and 4th are more common, you can choose according to habits.
The above code appeared in JS Common prototype, then prototype what is the use? Here's a look at:
varDom =function(){ }; Dom. Show=function() {alert ("Show Message"); }; Dom.prototype.Display=function() {alert ("Property Message"); }; Dom. Display (); //ErrorDom. Show (); varD =NewDom (); D.display (); D.show (); //Error
We first declare a variable and assign it to him because each function in JavaScript has a Portotype property, and the object does not. Add two methods to add and add the broken prototype, respectively, to see the downward use situation. The analysis results are as follows:
1, do not use the prototype attribute definition of the object method, is a static method, can only be called directly with the class name! In addition, the This variable cannot be used in this static method to invoke other properties of the Object!
2. Using the object method defined by the prototype attribute is a non-static method that can only be used after instantiation! Its method can be used internally to refer to other properties in the object itself!
Let's look at a piece of code here:
var function () { var Name = "Default"; this. Sex = "Boy"; This function () { alert ("Success"); }; }; Alert (DOM. Name); Alert (DOM. SEX);
Let's see first, what will it show? The answer is that all two show undefined, why? This is because each function in JavaScript forms a scope, and these variables are declared in the function, so they are in the scope of the function and cannot be accessed externally. To access a variable, you must make a new instance of it.
var html = { Name:' Object ', Success:function() { this function() { alert ("Hello,world"); }; Alert ("OBJ Success"); } ;
Look at this writing, in fact, this is a JavaScript "syntax Sugar", which is equivalent to:
?
1234567 |
var html =
new Object();
html.Name =
‘Object‘
;
html.Success =
function
(){
this
.Say =
function
(){
alert(
"Hello,world"
);
};
alert(
"Obj Success"
);
|
The variable HTML is an object, not a function, so there is no prototype property, and its methods are public methods, and HTML cannot be instantiated. Otherwise, an error will occur.
But he can be assigned as a value to other variables, such as var o = html; We can use it this way:
Alert (HTML. Name); Html. Success ();
Speaking of which, are we done? Careful people will ask, how to access the success method in the Say method? is HTML. Success.say ()?
No, of course not. Because of scope constraints, it is not accessible. So use the following method to access:
var New HTML. Success (); S.say (); // you can write it out . function () { alert ("HaHa");}; var New HTML. Success (); S.show ();
On the JavaScript scope of the problem, not one or two words can be said clearly, interested people can find some information online to see.
Second, the use of JavaScript closures
In fact, we can do a lot of things by using closures. such as simulating object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.
1. Anonymous self-executing function
We know all the variables, and if we don't add the var keyword, the default will be added to the properties of the global object, so that the temporary variable added to the global object has a lot of disadvantages,
For example, other functions may misuse these variables, causing the global object to be too large to affect the access speed (because the value of the variable needs to be traversed from the prototype chain).
In addition to using the VAR keyword every time a variable is used, we often encounter a situation where a function needs to be executed only once and its internal variables are not maintained.
For example, if the UI is initialized, then we can use closures:
var data= { 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);}} ) (data);
We create an anonymous function and execute it immediately, since the external cannot reference its internal variables, so the resources are freed immediately after the function is executed, and the key is not to pollute the global object.
2. Result Cache
We will encounter a lot of situations in the development, imagine that we have a process is a time-consuming function object, each call will take a long time,
Then we need to store the calculated value, when the function is called, first in the cache to find, if not found, then calculate, and then update the cache and return the value, if found, directly return the value to find. Closures can do this because it does not release external references, so values inside the function can be preserved.
varCachedsearchbox = (function(){ varCache ={}, Count= []; return{attachsearchbox:function(DSID) {if(DsidinchCache) {//If the result is in the cache returnCACHE[DSID];//directly returns objects in the cache } varFSB =NewUikit.webctrl.SearchBox (DSID);//NewCACHE[DSID] = FSB;//Update Cache if(Count.length > 100) {//the size of the positive cache <=100 DeleteCache[count.shift ()]; } returnFSB; }, Clearsearchbox:function(DSID) {if(Dsidinchcache) {cache[dsid].clearselection (); } } }; })(); Cachedsearchbox.attachsearchbox ("Input");
This will then be read from the cache when we call the second time.
3. Encapsulation
varperson =function(){ //variable scope is inside function, external unreachable varName = "Default"; return{getName:function(){ returnname; }, SetName:function(newName) {name=NewName; } } }(); Print (person.name);//direct access with a result of undefinedprint (Person.getname ()); Person.setname ("Abruzzi"); Print (Person.getname ()); The results are as follows: undefineddefaultAbruzzi
4. Implementing Classes and Inheritance
functionPerson () {varName = "Default"; return{getName:function(){ returnname; }, SetName:function(newName) {name=NewName; } } }; varp =NewPerson (); P.setname ("Tom"); Alert (P.getname ()); varJack =function(){}; //inherit from personJack.prototype =NewPerson (); //Adding Private methodsJack.prototype.Say =function() {alert ("Hello,my name is Jack"); }; varj =NewJack (); J.setname ("Jack"); J.say (); Alert (J.getname ());
We define the person, it is like a class, we new a person object, access its methods.
Here we define Jack, inherit the person, and add your own method.
Originally from: http://www.codeceo.com/article/javascript-bibao.html
JavaScript closure in-depth analysis and implementation method