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

Source: Internet
Author: User
Tags variable scope

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 kind of notation

functionthis. r == 3.14159functionreturn  This isvarnew Circle (1.0); alert (C.area ()); 

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

The 2nd kind of notation

var function  varnew= 3.14159functionreturnthis . PI * R *returnvarnew1.0);

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

The 3rd kind of notation

var New  = 3.14159functionreturnthis. PI * R *1.0));

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

The 4th kind of notation

var circle="PI": 3.14159"area":functionreturnthis. 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 kind of notation

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

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 function  function() {alert ("Show Message"function() {Alert ("property Message "//errorvarnew// 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 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() {  thisfuncti    on() {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 'function() {  thisfunction() {alert ("Hello  , world "); };
alert ("OBJ Success");
};

The variable HTML is an object, not a function, so there is no prototype property, its methods are public methods, HTML cannot be instantiated, otherwise an 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 ();

You can write it out.

function () {alert ("HaHa");}; var 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 purpose of the JavaScript closure

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 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, we often encounter a situation where a function needs to be executed only once, its internal variables are not maintenance-free,
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 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.

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. Encapsulation

var person = function () {
Variable scope is inside function, external unreachable
var name = "Default";

return {
Getname:function () {
return name;
},
Setname:function (newName) {
name = NewName;
}
}
}();

Print (person.name);//direct access with result of 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 ();
Adding Private methods
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.
We define Jack, inherit the person, and add our 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.