Transferred from: http://www.cnblogs.com/yunfeifei/p/4019504.html
Long time no blog, after a 11 vacation has become lazy, and today is finally the state of recovery. OK, let's get to the point, today I'll talk about the closure in JavaScript! This blog mainly talk about some practical things, mainly the closure of the wording, usage and use.
First, what is the closure and closure of several ways of writing and usage
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.
Simply put, 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 notation function Circle (r) { THIS.R = r;} Circle.pi = 3.14159functionThisnew Circle (1.0
There is nothing special about this notation, just adding some attributes to the function.
The 2nd notation function() { new Object (); obj. PI = 3.14159function this. PI * R *returnnew
The notation is to declare a variable and assign a function as a value to the variable.
The 3rd way of writing new Object (); Circle.pi = 3.14159function this. PI * R *
This method is best understood, that is, the new object, and then add properties and methods to the object.
The 4th way var circle={ "PI": 3.14159, "area":function this. PI * R *
This method is used more and is most convenient. var obj = {} is the declaration of an empty object.
the 5th type is the new Function ("this"). PI = 3.14159;this.area = function (r) {return r*r*this. PI;} " ); Alert ((
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:
function() { }; function() { alert ("Show message"function() {Alert ("Property Message"//error New//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:
function() { var Name = "Default"; This . Sex = "Boy"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() { function()} {alert ("Hello, World "); }; Alert ("Obj Success");};
Look at this writing, in fact, this is a JavaScript "syntax Sugar", which is equivalent to:
New Object (); Html. Name = ' Object '; functionfunction() {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, the following 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:
New HTML. Success (); S.say (); //function() {alert ("HaHa");}; 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 = for(var j = 0; J < Row.cells; i++
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.
var Cachedsearchbox = (function(){var cache ={}, Count =[];Return{attachsearchbox:function(DSID) {if (dsidIn cache) {//If the result is in the cachereturn CACHE[DSID];//Directly returns objects in the cache}var FSB = new Uikit.webctrl.SearchBox (DSID); // new CACHE[DSID] = FSB; // update cache if ( Count.length > {// the size of the positive cache <=100 delete Cache[count.shift ()];} return FSB;}, Clearsearchbox: function (DSID) {if (Dsid in cache) {cache[dsid].clearselection ();}} }; })(); Cachedsearchbox.attachsearchbox ("input");
This will then be read from the cache when we call the second time.
3. Encapsulation
var person =function(){//var name = "Default" ; return {getName: () {return Name }, SetName: function (newName) {name = NewName; } } }(); Print (person.name); // direct access with the result undefined default Abruzzi
4. Implementing Classes and Inheritance
functionPerson () {var name = "Default";Return{getName:function(){ReturnName }, SetName:function(NewName) {name =NewName; } } };var p =new); Alert (P.getname ());
var Jack = function// inherit from person Jack.prototype = new person (); // add private Method Jack.prototype.Say = function () {alert ("Hello,my name is Jack" ); }; var j = new Jack (); J.setname ("Jack"
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.
Personal Summary:
I used to think JavaScript was just a branch of Java, a scripting language, easy to learn, and now it's really a lot of things to learn. JavaScript is much more powerful than we think.
A full understanding of how JavaScript closures and closures are written and used