JavaScript Basics (27) Closure 2

Source: Internet
Author: User
Tags closure variable scope

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.

(1) The 1th kind of wording:

function Circle (r) {        this. R = r;  }    = 3.14159;   function () {    returnthis. R;  }     var New Circle (1.0);     Alert (C.area ());

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

(2) The 2nd kind of wording:

var function () {     varnew  Object ();      = 3.14159;           function (r) {         returnthis. PI * R * r;     }      return obj;  }     var New Circle ();   1.0));

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

(3) The 3rd kind of wording:

var New Object ();   = 3.14159;   function (r) {         returnthis. PI * R * r;  }     1.0));  

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

(4) The 4th kind of wording:

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. var obj = {} is the declaration of an empty object.

(5) The 5th kind of wording:

var New Function ("this. PI = 3.14159;this.area = function (r) {return r*r*this. PI;} " );    Alert ((new

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 Mess    Age " = function   () {alert    ( property Message  // 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, add and add directly above the prototype, and see the downward usage.

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 function () {        var Name = "Default";         this. Sex = "Boy";          This 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  function() {                    alert ("Hello,world");            };            Alert ("OBJ Success");        }    ;

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

    var New Object ();     = ' Object ';     function () {            thisfunction() {                    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 New HTML. Success (); S.say (); // you can write it out . function () {    alert ("HaHa");}; var New HTML. Success (); S.show ();

3. Use of 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 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 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 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 computed 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, return directly to the value you are looking for. 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) package

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 ()); The results are as follows: undefineddefaultAbruzzi

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

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.

JavaScript Basics (27) Closure 2

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.