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 the closure of the package

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.

2, the closure of several ways of writing and usage

The first thing to understand is that in JS everything is an object, and a 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.

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

There is nothing special about this notation, just adding some attributes to the function.

The 2nd way  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));  

The notation is to declare a variable and assign a function as a value to the variable.

The 3rd kind of notation  var Circle = new Object ();  Circle.pi = 3.14159;  Circle.area = function (r) {         return this. PI * R * r;  }    Alert (Circle.area (1.0));  

This method is best understood, that is, the new object, and then add properties and methods to the object.

The 4th way  var circle={     "PI": 3.14159,   "area": function (r) {            return). PI * R * r;          }  ;  Alert (Circle.area (1.0));  

This method is used more and is most convenient. var obj = {} is the declaration of an empty object.

The 5th type is  var Circle = new Function ("this"). PI = 3.14159;this.area = function (r) {return r*r*this. PI;} ");    Alert ((New Circle ()). Area (1.0));  

To tell the truth, this kind of writing I did not use, we can refer to.

In general, the above several methods, 2nd and 4th are more common, you can choose according to habits.

The above code appeared in JS Common prototype, then prototype what is the use? Here's a look at:

    var dom = function () {            };    Dom. Show = function () {        alert ("Show Message");    };        Dom.prototype.Display = function () {        alert ("Property Message");    };    Dom. Display (); Error    dom. Show ();      var d = new Dom ();    D.display ();    D.show (); Error

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 analysis results are as follows:

1, do not use the prototype attribute definition of the object method, is a static method, 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 piece of code here:

var dom = function () {        var Name = "Default";        This. Sex = "Boy";        this.success = function () {            alert ("Success");        };    }    ; Alert (DOM. Name);    Alert (DOM. SEX);

Let's see first, what will it show? 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.

var html = {        Name: ' Object ',        success:function () {this            . Say = function () {                    alert ("Hello,world");            };            Alert ("OBJ Success");        }    ;

Look at this writing, in fact, this is a JavaScript "syntax Sugar", which is equivalent to:

    var html = new Object ();    Html. Name = ' Object ';    Html. Success = function () {this            . Say = function () {                    alert ("Hello,world");            };            Alert ("OBJ Success");

The variable 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 occur:

But he can be assigned as a value to other variables, such as var o = html; We can use it this way:

    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, of course not. Because of scope constraints, it is not accessible. So use the following method to access:

var s = new HTML. Success (); S.say ();//can also write to the outside of HTML. Success.prototype.Show = function () {    alert ("HaHa");}; var s = new HTML. Success (); S.show ();

On the JavaScript scope of the problem, not one or two words can be said clearly, interested people can find some information online to see.

Second, the use of JavaScript 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 function

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 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 Cache

We will encounter a lot of situations in the development, imagine that we have a process is a time-consuming function object, each call will take a long time,

Then we need to store the calculated value, when the function is called, first in the cache to find, if not found, then calculate, and then update the cache and return the value, if found, directly return the value to find. Closures can do this because it does not release external references, so values inside the function can be preserved.

var Cachedsearchbox = (function () {        var cache = {},           count = [];        return {           attachsearchbox:function (dsid) {               if (Dsid in cache) {//If the result is returned in the cache                  cache[dsid];//returns the object in the cache directly               }               var FSB = new Uikit.webctrl.SearchBox (DSID);//New               Cache[dsid] = fsb;//Update Cache               if (count.length > 100) {//Yasumasa cache size <=100                  Delete cache[count.shift ()];               }               return FSB;                 },                clearsearchbox:function (dsid) {               if (Dsid in cache) {                  cache[dsid].clearselection () ;                 }           }        };    }) ();         Cachedsearchbox.attachsearchbox ("input");    

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

3. Encapsulation

var person = function () {        //variable scope is inside function, external cannot access        var name = "Default";                  return {           getname:function () {               return name;           },           setname:function (newName) {               name = NewName;           }        }    } ();         Print (person.name);//Direct access with the result of undefined    print (Person.getname ());    Person.setname ("Abruzzi");    Print (Person.getname ());       The results are as follows:     undefined  default  Abruzzi  

4. Implementing Classes and Inheritance

function person () {        var name = "Default";                  return {           getname:function () {               return name;           },           setname:function (newName) {               name = NewName;           }        }        };       var p = new person ();    P.setname ("Tom");    Alert (P.getname ());
var Jack = function () {}; Inherit from person jack.prototype = new Person (); Add Private method Jack.prototype.Say = function () { alert ("Hello,my name is Jack"); }; var j = new Jack (); J.setname ("Jack"); J.say (); Alert (J.getname ());

We define the person, it is like a class, we new a person object, access its methods.

Here we define Jack, inherit the person, and add your own method.

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

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.