Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of js closure_Basic knowledge

Detailed explanation of the use of js closure_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:31:451625browse

Let’s take a look at the uses of closures. In fact, by using closures, we can do a lot of things. For example, it can simulate the object-oriented coding style; express the code more elegantly and concisely; and improve the execution efficiency of the code in some aspects.

1 Anonymous self-executing function

We know all variables. If you do not add the var keyword, they will be added to the properties of the global object by default. There are many disadvantages to adding such temporary variables to the global object,
For example: other functions may misuse these variables; causing the global object to be too large and affecting 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 such a situation in actual situations, that is, some functions only need to be executed once, and their internal variables do not need to be maintained.
For example, for UI initialization, we can use closures:

Copy code The 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 create an anonymous function and execute it immediately. Since the variables inside it cannot be referenced from the outside,
Therefore, it will be released soon after execution. The key is that this mechanism will not pollute the global object.

2 cache

Let’s look at another example. Imagine we have a function object whose processing is very time-consuming. Each call will take a long time,

Then we need to store the calculated value. When calling this function, first search it in the cache. If it cannot be found, then calculate it,

Then update the cache and return the value. If found, just return the found value directly. Closures do exactly this because they do not release external references,

Thus the value inside the function can be preserved.


Copy code The 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]; // Return to the object in the cache directly
                                                                                  var fsb = new uikit.webctrl.SearchBox(dsid);//New  
               cache[dsid] = fsb;//Update cache                                                               If (count.length & gt; 100) {// The size of the cache cache; = 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 the object from the cache without creating a new searchbox object.

3 Implement encapsulation

You can first look at an example of encapsulation. The internal variables cannot be accessed outside the person, but can be accessed by providing a closure:


Copy code

The code is as follows:

var person = function(){  //Variable scope is inside the function and cannot be accessed from the outside var name = "default"; var name                           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 use of closures is to implement objects in object-oriented. Traditional object languages ​​provide class template mechanisms,
In this way, different objects (instances of classes) have independent members and states and do not interfere with each other. Although there is no mechanism like classes in JavaScript, by using closures,
We can simulate such a mechanism. Let’s take the example above:



Copy code



The code is as follows:


function Person(){ 
var name = "default"; var name
                         
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 results are as follows:

default
john
default jack

It can be seen from this code that both john and jack can be called instances of the Person class, 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. It is very simple and easy to understand. I hope it will be helpful to my friends

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn