JavaScript closures are a very interesting thing. After reading some related information //www.VeVB.COM/article/29472.htm, the most impressive thing about it is: it realizes public and private.
The easiest syntax to create a non-anonymous closure is:
The code copy is as follows:
var obj = (function(){//various codes});
The most classic example of closures:
The code copy is 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:
The code copy is as follows:
var makeCounter= (function () {
var i = 1;
//This is private
function log(){
console.log(i);
i++;
}
//This guy 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 I saw such a code, I felt: so advanced;
The code copy is as follows:
var obj = (function(window){
//A variety of codes
}(window));
Then I went to Google and found that they often write like this:
The code copy is 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 and write two steps into one step.
The code copy is as follows:
//This is a function. It should use obj() like this
var makeCounter = function () {
//A variety of codes
}
//This is an object. It's similar to var obj = makeCounter();
var obj = (function () {
//A variety of codes
}());
It can also have parameters:
The code copy is 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 advanced:
The code copy is as follows:
var output = "new test";
var obj = (function (obj, msg) {
//This guy is also private. Similar to obj.i(!=obj.i), but not obj.i (because it is inaccessible externally).
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 has not been changed
obj.test(); // 2 : new test
The first time we met, we left a deep impression. The use of closures realizes the maintenance of state and attributes; avoids the flying of global variables on the screen; ends the embarrassing situation where variables are always redefined and reassigned. It can also segment an object into multiple js files. It's really great.
The above is the entire content of this article, I hope you like it.