The function of the closure in JS

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.