Js closure Usage Details, js Usage Details

Source: Internet
Author: User
Tags variable scope delete cache

Js closure Usage Details, js Usage Details

Let's take a look at the purpose of the closure. In fact, we can do a lot of things by using closures. For example, it simulates the object-oriented code style. It is more elegant and concise to express the Code. In some aspects, it improves the code execution efficiency.

1. Anonymous self-execution function

We know all the variables. If the var keyword is not added, it will be added to the global object attribute by default. There are many disadvantages for adding such temporary variables to the global object,
For example, other functions may misuse these variables, resulting in a huge global object that affects access speed (because the value of the variable needs to be traversed from the prototype chain ).
Except that variables are used with the var keyword each time, we often encounter such a situation that some functions only need to be executed once and internal variables do not need to be maintained,
For example, we can use the closure to initialize the UI:

Copy codeThe Code is as follows:
Var datamodel = {
Table: [],
Tree :{}
};

(Function (dm ){
For (var I = 0; I <dm. table. rows; I ++ ){
Var row = dm. table. rows [I];
For (var j = 0; j <row. cells; I ++ ){
DrawCell (I, j );
}
}

// Build dm. tree
}) (Datamodel );

We created an anonymous function and immediately executed it. Because the external system cannot reference its internal variables,
Therefore, it will be released soon after execution. The key is that this mechanism will not pollute global objects.

2 Cache

Let's take a look at an example. Suppose we have a function object that takes a long time to process, and each call will take a long time,
Then we need to store the calculated value. When calling this function, we first search for it in the cache. If it cannot be found, we will calculate it,
Then update the cache and return the value. If yes, return the value. The closure can do this because it does not release external references,
So that the internal values of the function can be retained.

Copy codeThe Code is as follows:
Var CachedSearchBox = (function (){
Var cache = {},
Count = [];
Return {
AttachSearchBox: function (dsid ){
If (dsid in cache) {// if the result is in the cache
Return cache [dsid]; // directly return the objects in the cache
}
Var fsb = new uikit. webctrl. SearchBox (dsid); // create
Cache [dsid] = fsb; // update cache
If (count. length> 100) {// keep the cache size <= 100
Delete cache [count. shift ()];
}
Return fsb;
},

ClearSearchBox: function (dsid ){
If (dsid in cache ){
Cache [dsid]. clearSelection ();
}
}
};
})();

CachedSearchBox. attachSearchBox ("input1 ");

In this way, when we call CachedSearchBox. attachSerachBox ("input1") for the second time,
We can retrieve this object from the cache without creating a new searchbox object.

3. Encapsulation

Let's take a look at an example of encapsulation. variables outside of person cannot be accessed, but they are accessed by providing closures:

Copy codeThe Code is as follows:
Var person = function (){
// The variable scope is inside the function and cannot be accessed from outside.
Var name = "default ";

Return {
GetName: function (){
Return name;
},
SetName: function (newName ){
Name = newName;
}
}
}();

Print (person. name); // direct access, the result is undefined
Print (person. getName ());
Person. setName ("abruzzi ");
Print (person. getName ());

The result is as follows:

Undefined
Default
Abruzzi
 
4. Another important purpose of closures is to implement objects in object-oriented systems. Traditional object Languages provide class templates,
In this way, different objects (instance of the class) have independent members and States and do not interfere with each other. Although JavaScript does not have a mechanism like this, by using closures,
We can simulate this mechanism. In the above example:

Copy codeThe Code is as follows:
Function Person (){
Var name = "default ";

Return {
GetName: function (){
Return name;
},
SetName: function (newName ){
Name = newName;
}
}
};


Var john = Person ();
Print (john. getName ());
John. setName ("john ");
Print (john. getName ());

Var jack = Person ();
Print (jack. getName ());
Jack. setName ("jack ");
Print (jack. getName ());

The running result is as follows:

Default
John
Default
Jack
From this code, we can see that john and jack can both be called the Person class instances, because the two instances have independent access to the name Member and do not affect each other.

The above is the function of js closure, which is very easy to understand. I hope it will be helpful to my friends.

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.