The use of JS closures

Source: Internet
Author: User
Tags variable scope

Let's take a look at the use of closures. In fact, we can do a lot of things by using closures. such as simulating object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.

1 anonymous self-executing functions

We know all the variables, and if we don't add the var keyword, the default will be added to the properties of the global object, so that the temporary variable added to the global object has a lot of disadvantages,
For example, other functions may misuse these variables, causing the global object to be too large to affect the access speed (because the value of the variable needs to be traversed from the prototype chain).
In addition to using the VAR keyword every time a variable is used, we often encounter a situation where a function needs to be executed only once and its internal variables are not maintained.
For example, if the UI is initialized, then we can use closures:

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 immediately executed it, because the external cannot reference its internal variables,
So it will be released soon after execution, and the key is that this mechanism will not pollute the global object.

2 Cache

Take another example and imagine that we have a function object that is time-consuming to process, and that it takes a long time for each call to be
Then we need to store the calculated value, when the function is called, first in the cache to find, if not found, then calculate,
It then updates the cache and returns the value, and if it finds it, returns the found value directly. Closures are exactly what you can do because it does not release external references,
Thus the values inside the function can be preserved.

varCachedsearchbox = (function(){      varCache ={}, Count= []; return{attachsearchbox:function(DSID) {if(DsidinchCache) {//If the result is in the cache              returnCACHE[DSID];//directly returns objects in the cache           }             varFSB =NewUikit.webctrl.SearchBox (DSID);//NewCACHE[DSID] = FSB;//Update Cache           if(Count.length > 100) {//the size of the positive cache <=100              DeleteCache[count.shift ()]; }             returnFSB; }, Clearsearchbox:function(DSID) {if(Dsidinchcache)               {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 take the object from the cache.

3 Implementing Encapsulation

You can start by looking at an example of encapsulation, where you cannot access the variables inside of a person, but by providing closures:

varperson =function(){      //variable scope is inside function, external unreachable    varName = "Default"; return{getName:function(){             returnname; }, SetName:function(newName) {name=NewName;     }      }  }(); Print (person.name);//direct access with a result of undefinedprint (Person.getname ()); Person.setname ("Abruzzi");   Print (Person.getname ()); The results are as follows: undefineddefaultAbruzzi
4 Object-oriented

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

functionPerson () {varName = "Default"; return{getName:function(){             returnname; }, SetName:function(newName) {name=NewName;        }      }  }; varJohn =Person ();  Print (John.getname ()); John.setname ("John");     Print (John.getname ()); varJack =Person ();  Print (Jack.getname ()); Jack.setname ("Jack");   Print (Jack.getname ()); The results of the operation are as follows:defaultJohndefaultJack

This code shows that both John and Jack can be referred to as instances of the person class, because these two instances have independent, non-impact access to the name member.

In addition for reprint

The use of JS closures

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.