An in-depth analysis of the functions and implementation of JavaScript closures _javascript skills

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

One, what are the types and usage of closures and closures                                                          &NBSP
1, what is a closure
closure, The official explanation for closures is that an expression (usually a function) with many variables and an environment bound to those variables is also part of the expression. Closure Features:
1). As a reference to a function variable, it is active when the function returns.
2). A closure is when a function returns, a stack area that does not release resources.
Simply put, JavaScript allows you to use internal functions-that is, function definitions and function expressions that are in the function body of another function. Furthermore, these internal functions can access all the local variables, arguments, and other internal functions declared in the external function in which they are located. A closure is formed when one of these intrinsic functions is called outside the external function that contains them.
2, several methods and usages of closures
First of all understand that in JS everything is an object, function is an object. Let's take a look at the closure of the 5 kinds of writing, a simple understanding of what is closure. will be explained in detail later.

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's nothing special about this writing, just adding some properties to the function.

The 2nd way to spell 
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 writing is to declare a variable and assign a function as a value to the variable.

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

Alert (Circle.area (1.0));

The best way to understand this approach is to new an object and then add properties and methods to the object.

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

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

The 5th way to spell 
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, I did not use this type of writing, we can refer to.
In general, the above methods, 2nd and 4th are more common, you can choose according to Custom.
The above code appears in the JS commonly used prototype, then prototype what use? Let's take a look at the following:

var dom = function () {

  };

  Dom. Show = function () {
    alert (' Show message ');

  Dom.prototype.Display = function () {
    Alert ("Property message");

  Dom. Display (); The error
  dom. Show (); 
  var d = new Dom ();
  D.display ();
  D.show (); Error

We first declare a variable, assign a function to him, because each function in JavaScript has a Portotype property, and the object does not. Add two methods to directly add and add broken prototype above, to see the downward use situation. The analysis results are as follows:
1, does not use the prototype attribute definition object method, is the static method, can only directly use the class name to make the call! In addition, the This variable cannot be used in this static method to invoke other properties of the Object!
2. The object method defined by using the prototype property is a Non-static method, which can only be used after instantiation! Within its method, this can be used to refer to other properties in the object itself!

Let's take another look at the code:

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

  ;}; Alert (DOM. Name);
  Alert (DOM. SEX);

Let's have a look, what will it show? The answer is two show undefined, why? This is because each function in JavaScript forms a scope that is declared in a function, so it is in the scope of the function and is inaccessible outside. To access a variable, you must come out with a new instance.

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

Look at this type of writing, in fact, this is a JavaScript "grammatical sugar", which is equivalent to:

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

Variable HTML is an object, not a function, so there is no prototype property, and its methods are public, and HTML cannot be instantiated. Otherwise, you will receive the following error:

But he can assign to other variables as values, such as var o = html; We can use it this way:
alert (HTML. Name);
Html. Success ();
speaking of which, is it over? Careful people will ask, how to access the Say method in the success method? is HTML. Success.say ()?
Of course not, I just said it's not accessible because of scope limitations. So the following method is used to access:

var s = new HTML. Success ();
S.say ();

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

About JavaScript scope problem, not one or two words can be clear, interested people can find some information on the Internet to see.
second, the use of JavaScript closures
In fact, we can do a lot of things by using closures. For example, simulate object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.

1. Anonymous self-execution function
We know all the variables, if not the var keyword, then the default is added to the global object's properties, such a temporary variable to join the global object has a lot of disadvantages,
For example, other functions may misuse these variables, causing the global object to be too large, affecting the speed of access (because the value of the variable is required to traverse from the prototype chain).
In addition to using the var keyword for each variable, we often encounter situations where a function needs to be executed only once and its internal variables need not be maintained, such as the UI initialization, so 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 created an anonymous function and executed it immediately, because the outside cannot reference its internal variables, so when the function is finished, the resources are released immediately, and the key is not to pollute the global object.

2. Result caching
We run into a lot of situations in our development, and imagine that we have a function object that is time-consuming to process, and that it takes a long time to make each call,
Then we need to store the calculated value, when the function is called, first look in the cache, if it is not found, then calculate, then update the cache and return the value, if found, directly return the lookup value. Closures can do this because it does not release external references, so the values within 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];//directly returns the object in the cache  
      }  
      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");

So we read the object from the cache the second time it is called.

3, Packaging

The var person = function () {  
  //variable scope is inside of functions and cannot be accessed outside of  
  var name = ' Default ';    

  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 results were 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's like a class, we're new to a person object, to access its method.
Here we define jack, inherit person, and add our own method.
Personal Summary:
previously thought JavaScript is just a branch of Java, is a scripting language, it is easy to learn, and now found that there are really a lot of things to learn. JavaScript is a lot more powerful than we think.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.