1, execute the self-executing function. Some functions may only need to be executed once and in order not to cause global pollution. Declaring a variable requires VAR, otherwise it is added to the properties of the global object by default. or another function might misuse the property. If the global object is too large, it will affect the speed of access. (The value of the variable needs to be traversed from the prototype chain)
(function (value) {
Console.log (value)
}) (3);
2. As a cache. The second time you use an object, you don't have to create a new object. The implementation of the singleton pattern and so on.
var cache= (function () {
var cache={};
return{
Getobj:function (name) {
if (name in cache) {
return Cache[name];
}
var temp=new Object (name);
Cache[name]=temp;
return temp;
}
}
})()
3, the implementation of the packaging process. The variables in the encapsulated object cannot be accessed directly, and the provided closed packet access is mentioned.
var person=function () {
var name= "no name!";
return {
Getname:function () {
return this.name;
},
Setname:function (value) {
This.name=value;
}
}
}()
4. Implement object-oriented
Summary: Closures are functions returned in other functions that can access variables inside the function that return the function!
The function of the closure in JS