A comprehensive understanding of how JavaScript closures and closures are written and used

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

first, what is the closure and closure of several ways of writing and usage
 1, what is closures   closures, the official explanation for closures is that an expression (usually a function) with many variables and environments that bind these variables is also part of the expression. Features of closures: 1.  As a reference to a function variable, when the function returns, it is in the active state.  2. A closure is when a function returns, a stack that does not release resources. 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. Several methods and usages of    2 and closures   first of all to understand that in JS everything is an object, function is a kind of object. Let's take a look at the 5 types of closures, and simply understand what closures are. It will be explained in detail later.   Copy code//1th notation  function Circle (r) {       THIS.R = R;  }  circle.pi = 3.14159;  circle.prototype.area = function () {   return circle.pi * THIS.R * THIS.R;  }    var c = new Circle (1.0);     alert (C.area ());    Copy Code This is nothing special, just add some attributes to the function.   Copy code//2nd notation  var Circle = function () {    var obj = new Object ();     obj. PI = 3.14159;          obj.area = function (r) {        return this. PI * R * r;     }     return obj;  }    var C = new Circle ();  alert (C.area (1.0));   Copy Code This is the notation of declaring a variable, assigning a function as a value to the variable.   Copy Code//3rd notation  var Circle = new Object ();  circle.pi = 3.14159;  circle.area = function (r) {        return this. PI * R * r;  }    alert (Circle.area (1.0));   Copy Code This method is best understood, that is, the new object, and then add properties and methods to the object.   Copy Code//4th notation  var circle={     "PI": 3.14159,    "area": function (r) {           return this. PI * R * r;         }  };  alert (Circle.area (1.0));   Copy Code This method is used more and is most convenient. var obj = {} is the declaration of an empty object.  //5th notation  var Circle = new Function ("this". PI = 3.14159;this.area = function (r) {return r*r*this. PI;} ");    alert ((New Circle ()). Area (1.0));   Honestly, I don't use this kind of writing, we can refer to it.   In general, the above methods, 2nd and 4th are more common, you can choose according to habits.   The above code appeared in JS in the common prototype, then prototype what is the use of it? Let's look at the following: &NBSP; Copy code     var dom = function () {           };     DOM. Show = function () {        alert ("Show Message");   };        DOM.P Rototype. Display = function () {        Alert ("Property Message");   };     DOM. Display (); error    DOM. Show ();      var d = new Dom ();    D.display ();    d.show (); Error copy code We first declare a variable and assign it to him because each function in JavaScript has a Portotype property, and the object does not. Add two methods to add and add the broken prototype, respectively, to see the downward use situation. The results of the analysis are as follows:   1, the object method not defined with the prototype attribute, is a static method and can only be called directly with the class name!   In addition, the This variable cannot be used in this static method to invoke other properties of the Object! 2. Using the object method defined by the prototype attribute is a non-static method that can only be used after instantiation! Its method can be used internally to refer to other properties in the object itself!     let's look at a snippet of code:  copy code var dom = function () {        var Name = "Default";  &nbs P     this. Sex = "Boy";        this.success = function () {      &NBSP     Alert ("Success");       };   };     alert (DOM. Name);    alert (DOM. SEX); Copy the code let's see what we can show you first. The answer is that all two show undefined, why? This is because each function in JavaScript forms a scope, and these variables are declared in the function, so they are in the scope of the function and cannot be accessed externally. To access a variable, you must make a new instance of it.   Copy Code var html = {        Name: ' Object ',        Success:function ( ) {            this. Say = function () {                    alert ("Hello,world");           };            alert ("OBJ Success");       }    ; Copy the code and look at the notation, which is a "syntactic sugar" of JavaScript, which is equivalent to:  copy code     var html = new Object ();    HTML. Name = ' Object ';    HTML. Success = function () {            this. Say = function () {                   Alert ("Hello,world");           };            alert ("O BJ Success "); Copy code variables HTML is an object, not a function, so there is no prototype property, and its methods are public methods, and HTML cannot be instantiated. Otherwise, the following error will appear:    but he can be assigned as a value to other variables, such as var o = html; We can use it like this:     alert (HTML. Name);    HTML. Success (); Speaking of which, are we done? Careful people will ask, how to access the success method in the Say method? is HTML. Success.say ()?   No, I just said it. Because of scope limitations, it is not accessible. So use the following method to access the:  copy code var s = new HTML. Success (); S.say ();  //can also write out HTML. Success.prototype.Show = function () {    alert ("HaHa");}; var s = new HTML. Success (); s.show (); Copy the code about the JavaScript scope of the problem, not one or two words can be said clearly, interested people can find some information online to see.     JavaScript closure use                         &N Bsp                          ,         &NB Sp      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 you do not add the var keyword, the default is added to the properties of the global object, so that 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, affecting the access speed ( Because the values of the variables need 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 we have a time-consuming function object, each call will take a long time,  then we need to store the computed value. When this function is called, it is first found in the cache, if it is not found, it is evaluated, then the cache is updated and the value is returned, if the, return directly to the value you have found. 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 ()];               }          &NBSp    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;   &NBSP;&NBSP;     &NBSP,           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) {  &NB sp;        &NBsp  name = NewName;           }       }       };        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.

A comprehensive understanding of how JavaScript closures and closures are written and used

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.