Summary of principle and usage of closure in JavaScript

Source: Internet
Author: User
Tags closure object object variable scope delete cache

The five forms of closure in JavaScript are as follows:

1 /**2 * Created by admin on 2016/12/26.3  *//*4 //Add a property to a function object5 function Circle (r) {6 this.r=r;7 }8 circle.prototype.pi=3.1415926;9 circle.prototype.area=function () {Ten return this. PI*THIS.R*THIS.R; One }; A var c=new Circle (); - Console.log ("is:" + c.area (1.0)); -  the //Creates a new object object, adds a property to it, and returns the object - var circle=function () { - var obj=new Object (); - obj. pi=3.1415926; + Obj.area=function (r) { - return this. pi* R*r; +     } A return obj; at } - var c=new Circle (); - Console.log ("is:" + c.area (1.0)); -  - //Create a new object and add properties to it - var circle=new Object (); in circle.pi=3.1415926; - Circle.area=function (r) { to return this. Pi*r*r; + } - Console.log ("is:" + circle.area (1.0)); the  * //Directly constructs an object that declares properties and methods $ var circle={Panax Notoginseng ' PI ': 3.1415926, - ' area ': function (r) { the return this. Pi*r*r; +     } A } the Console.log (' Area: ' +circle.area (1.0)); + //Using a JavaScript built-in function object to construct an object circle, note that the variable it constructs is a global variable, and each call to a Circle object invokes function, which is less used in the loop.  - var circle=new Function ("this. Pi=3.1415926;this.area=function (r) {return this. Pi*r*r;} "); $ Console.log (' area: ' + (new Circle). Area (1.0));
View Code

Second, the use of closures

Second, JavaScript closure for use                             &NB Sp                          ,         &NB SP;

  In fact, 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.  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 variables added to the global object have many disadvantages, such as: Other functions may misuse these variables, causing the global object is too large, Affects access speed (because the value of a variable is to be traversed from the prototype chain). In addition to using the VAR keyword every time, we often encounter a situation where a function needs to be executed only once and its internal variables need not be maintained, such as UI initialization, then we can use the closure:  to copy the code var data= {       table: [],        tree: {}    };          (function (DM) {       for (var i = 0; i < dm.table.rows; i++) {&nbs P         var row = dm.table.rows[i];           for (var j = 0; j < Row.cells; i++) {           &N Bsp  drawcell (i, j);           }       }           }) (data);    Copy Code we create an anonymous function and execute it immediately, since the external cannot reference the variables inside it, so the resource is freed immediately after the function is executed, and the key is not to pollute the global object. &NBSP;&NBSP;&NBSP;2, Results cache   We have a lot of situations in our development, imagine that we have a very time-consuming function object, eachThe call takes a long time,  then we need to store the computed value, and when this function is called, it is first found in the cache, if it is not found, then the cache is updated and the value is returned, and if it is 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.   Copy code var Cachedsearchbox = (function () {       var cache = {},           count = [];        Return {          attachsearchbox:function (DSID) {  &NBSP ;           if (Dsid in cache) {//If the results are in the buffer              &NB Sp   Return cache[dsid];//direct return to objects in cache               }               var FSB = new Uikit.webctrl.SearchBox (DSID);//new            &NBSP ; &NBSP;CACHE[DSID] = fsb;//Update cache               if (count.length > 100) {//Yasumasa cache Size & lt;=100                  Delete cache[count.shift ()];               }               return FSB;                 },               &NBS P;clearsearchbox:function (DSID) {              if (Dsid in cache) {   & nbsp             cache[dsid].clearselection ();                 }           }    &nbs P  };   &NBSP;}) ();         cachedsearchbox.attachsearchbox ("input");     Copy the code so that we read the object from the cache the second time we call it. &NBSP;&NBSP;&NBSP;3, encapsulation   copy code var person = function () {      //variable scope is inside function, external unreachable    & nbsp   var name = "Default";                  return {          getnam E:function () {              return name;           },           setname:function (newName) {  &NB sp;           name = NewName;           }       }    } ();         print (person.name);//direct access, resulting in undefined    print (Person.getname ());    person.setname ("Abruzzi");    print (Person.getname ());        results are as follows:     undefined  default  abruzzi   Copy Code   4, Implement class and inherit   copy code function person () {       var name = "Default";         &nbsp ;        Return {          getname:function () {     &nbs P        return name;           },          setname:function (newName) {              name = newName;   &NB sp;       }       }       };        var p = new person ();    p.setname ("Tom");    alert (P.getname ()); nbsp;    var Jack = function () {};   //Inherit from person    Jack.prototype = new Person ();  &NB Sp Add Private method     Jack.prototype.Say = function () {        alert ("Hello,my name is Jack");  &N Bsp };    var j = new Jack ();    j.setname ("Jack");    J.say ();    alert (J.getname ()); Copy code we define the person, it is like a class, we new a person object, access its methods.   Below we define Jack, inherit the person, and add your own method.

Summary of principles and usages of closures in JavaScript (go)

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.