JavaScript closures are an interesting stuff. Read some of the relevant information http://www.jb51.net/article/29472.htm, the most impressive is: the realization of public and private.
The simplest syntax for creating a non-anonymous closure is:
Copy Code code as follows:
var obj = (function () {//various code});
The most classic example of closures:
Copy Code code as follows:
var Makecounter = (function () {
var i = 1;
This.test=function () {
Console.log (i);
i++;
}
return this;
});
var obj = Makecounter ();
Obj.test (); 1
Obj.test (); 2
var obj1 = Makecounter ();
Obj1.test (); 1
Obj1.test (); 2
Private and public:
Copy Code code as follows:
var makecounter= (function () {
var i = 1;
This stuff is private.
function log () {
Console.log (i);
i++;
}
This stuff is public.
This.test () {
Log ();
}
return this;
});
var obj = Makecounter ();
Obj.test (); 1
Obj.test (); 2
Obj.log (); Undefined
Self-executing function:
The first time you see such a code feeling is: good high-level;
Copy Code code as follows:
var obj = (function (window) {
Various code
} (window));
And then google it and find that they often write this:
Copy Code code as follows:
var obj= (function () {
var i = 1;
This.test=function () {
Console.log (i);
i++;
}
return this;
}());
Obj.test (); 1
Obj.test (); 2
The simplest understanding is that programmers are lazy to write a two-step step.
Copy Code code as follows:
This is a function. It should be this way with obj ()
var makecounter = function () {
Various code
}
This is an object. It is similar to var obj = Makecounter ();
var obj = (function () {
Various code
}());
It can also have parameters:
Copy Code code as follows:
var output = "New test";
var obj = (function (msg) {
This.test = function () {
Console.log (msg);
}
return this;
} (output));
Obj.test ();
It can also be more complex and more advanced:
Copy Code code as follows:
var output = "New test";
var obj = (function (obj, msg) {
The goods are private, too. Similar to OBJ.I (!=OBJ.I), but not obj.i (because external inaccessible).
var i = 1;
Private
function log () {
Console.log (i + ":" + msg);
i++;
}
Public
Obj.test = function () {
Log ();
}
return obj;
} (obj, output));
Obj.test (); 1:new Test
OBJ.I = 100;
I have not been changed
Obj.test (); 2:new Test
The first meeting left a deep impression. The use of closures, the implementation of the State, the retention of attributes, to avoid the global variable full screen dancing, the end of the variable is always redefined, the embarrassing situation of the value of the assignment. It can also branch an object to more than one JS file. It's really good.
The above mentioned is the entire content of this article, I hope you can enjoy.