An analysis of the closure in JavaScript

Source: Internet
Author: User
Tags closure variable scope

The closure in JavaScript is really a commonplace problem, and the recent interview has been asked that my own ability to express can not be fully supported, really crazy. On the way back, I suddenly thought of a very simple thing, in fact, we do the project, in fact, often used to closure, but the interview when asked, the answer is often the answer we often search, alas, whether it is to meet the interview or really want to learn something, I also use their understanding to share with you, The writing will not be avoided.

  1. What is a closure?

  Red Book in the Middle Yue : "refers to a function that has access to a variable in another function scope. "

  Simply put, JavaScript allows the use of intrinsic functions---that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed. In other words, " one function creates another function inside, and this function can read the variable in the function above, and this function can be called ' closure '."

  2 What's the use of closures?

Through my extensive review, if we say "by using closures, we can do a lot of things." such as simulating object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code Execution ", will not feel very empty, that these will be better, because there is no real block-level scope in JavaScript, But in order for a function to declare some local variables that only the function can use, we use closures so that we can greatly reduce the variables in the global scope and purify the global scope .

Here are some examples:

   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, we often encounter a situation in which a function needs to be executed only once and its internal variables need not be maintained, such as the initialization of the UI, then we can use closures:
var data= {        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);}}           ) (data);   

We create an anonymous function and execute it immediately, since the external cannot reference its internal variables, so the resources are freed immediately after the function is executed, and the key is not to pollute the global object.

  2. Result caching

we will encounter a lot of situations in the development, imagine that we have a process very time-consuming function object, each call will take a long time, then we need to store the computed value, when called this function, first in the cache to find, if not found,    is evaluated, then the cache is updated and the value is returned, and if found, it is returned directly to the lookup value. Closures can do this because it does not release external references, so 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 ("Input");

This will then be read from the cache when we call the second time.

  3. Encapsulation

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 ()); 

4. Implementing Classes and Inheritance

functionPerson () {varName = "Default"; return{getName:function(){               returnname; }, SetName:function(newName) {name=NewName;        }        }        }; varp =NewPerson (); P.setname ("Tom");     Alert (P.getname ()); varJack =function(){}; //inherit from personJack.prototype =NewPerson (); //Adding Private methodsJack.prototype.Say =function() {alert ("Hello,my name is Jack");    }; varj =NewJack (); J.setname ("Jack");    J.say (); Alert (J.getname ());

Write to the end, do not know the last of you to find that they have done the project actually used a lot of this, anyway, I was met, closures is so always there.

About closures, although commonplace, but still very important. As for the closure of the defect well, just say a good is not dry goods abuse closure, will lead to memory leaks, memory leaks is what Baidu bar ^_^.

Thank you for your friends to see the last, I hope we can all be happy.

An analysis of the closure in JavaScript

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.