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");
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
Another important use of the 4 closures is to implement object-oriented objects, which provide a template mechanism for the class, and the traditional object language
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.
The use of JS closures