The use of JS closures

Source: Internet
Author: User
Tags anonymous object execution functions variables variable variable scope access

Let's look at the closure's purpose. In fact, we can do a lot of things by using closures. For example, simulate object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.


1 anonymous self-execution functions


We know all the variables, if not the var keyword, then the default is added to the global object's properties, such a temporary variable to join the global object has a lot of disadvantages,
For example, other functions may misuse these variables, causing the global object to be too large, affecting the speed of access (because the value of the variable is required to traverse from the prototype chain).
In addition to using the var keyword for each variable, we often encounter situations where a function needs to be executed once and its internal variables are not maintained.
such as the initialization of the UI, then we can use the closure:

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 

We created an anonymous function and executed it immediately, because the external cannot reference the variable inside it,
So it will be released soon after execution, and the key is that this mechanism will not pollute the global object.

2 Cache


To take another example, imagine that we have a function object that is time-consuming to process, and each call takes a long time,
Then we need to store the computed values, and when we call this function, we first look in the cache, and if we can't find it, we do the calculation.
It then updates the cache and returns the value, and if found, returns the lookup value directly. Closures are exactly what can be done because it does not release external references,
Thus the value within the function can be preserved.

var Cachedsearchbox = (function () {      var cache = {},         Count = [];      return {         attachsearchbox:function (dsi D {             if (dsid in cache) {//If result in cache     
             return cache[dsid];//directly returns the object in the cache             }              var FSB = new Uikit.webctrl.SearchBox (DSID);//New               Cache[dsid] = fsb;//Update cache              if ( Count.length > 100) {//Yasumasa cache size <=100                 Delete cache[count.shift ()];            }             return fsb;              },             clearsearchbox:function (DSID) {              if (dsid in cache) {                 cache[dsid].clearselection ();               }        }     }; }) ();     
;  Cachedsearchbox.attachsearchbox ("input1"); 

So, when we call Cachedsearchbox.attachserachbox ("INPUT1") for the second time,
Instead of creating a new SearchBox object, we can go through the object from the cache.

3 Implementation Package


You can take a look at an example of encapsulation, where you can't access variables outside of person, and access it by providing a closure:

 var person = function () {     //variable scope is inside function, outside inaccessible       var name = ' Default ";              return {          getname:function () {             return name;         },         setname:function (newName ) {             name = newname;         }     } } ();     print (person.name);/direct access, result is undefined
  Print (Person.getname ());  person.setname ("Abruzzi");  print (Person.getname ());    The results are as follows:   undefined default Abruzzi 

Another important use of

4 closures is to implement object-oriented objects, where traditional object languages provide template mechanisms for classes,
so that different objects (instances of the class) have independent members and states and do not interfere with each other. Although there are no such mechanisms in JavaScript,
We can simulate such a mechanism by using closures. Or in the example above:

 function person () {      var name = "Default";        & 
nbsp     return {         getname:function () {              return name;        },   & nbsp;     setname:function (newName) {              name = newname;        }     } };  &n bsp;     var john = person ();  print (John.getname ());  John.setname ("John");  print (joh 
N.getname ());     var jack = person ();  print (Jack.getname ());  jack.setname ("Jack");  Print (Jack.getname ());    Running results are as follows:   default John default Jack 

This code shows that both John and Jack can be referred to as instances of the class of person, since these two instances are independent and unrelated to the access of name to this member.



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.