What is JavaScript closure?

Source: Internet
Author: User

After using JavaScript for more than a year, the closure is always confusing. I have been familiar with some closures and made several mistakes due to my incomprehension of closures. I have read more information over a year, but I still don't quite understand it, recently I accidentally read the appendix of the basic jquery tutorial and found that appendix A's introduction to JavaScript closures is easy to understand.

 

1. Simple Example

First of all, from a classic error, there are several divs on the page. We want to bind them with an onclick method, so we have the followingCode

 <  Div  ID  = "Divtest"  >          <  Span  > 0 </  Span  >  <  Span  > 1 </  Span  >   <  Span  > 2 </  Span  >   <  Span  > 3 </  Span >      </  Div  >      <  Div  ID  = "Divtest2"  >          <  Span  > 0 </  Span  >   <  Span > 1 </  Span  >   <  Span  > 2 </  Span  >   <  Span  > 3 </  Span  >      </ Div  > 
 
$ (Document). Ready (Function(){VaRSpans = $ ("# divtest span");For(VaRI = 0; I <spans. length; I ++) {Spans [I]. onclick=Function() {Alert (I );}}});

A very simple function is wrong. Every time alert outputs a value of 4, it is easy to make a simple modification.

VaRSpans2 = $ ("# divtest2 span"); $ (Document). Ready (Function(){For(VaRI = 0; I <spans2.length; I ++){(Function(Num) {spans2 [I]. onclick=Function() {Alert (Num) ;}}) (I );}});

2. Internal functions

Let's start with some basic knowledge. First, let's take a look at internal functions. An internal function is a function defined in another function. For example:

FunctionOuterfn (){FunctionInnerfn (){}}

Innerfn is an internal function in the outerfn scope. This means that calling innerfn inside outerfn is valid, while calling innerfn outside outerfn is invalid. The following code causes a javascript error:

 

 
FunctionOuterfn () {document. Write ("Outer function <br/>");FunctionInnerfn () {document. Write ("Inner function <br/>") ;}} Innerfn ();

However, if innerfn is called within outerfn, the operation can be successful:

FunctionOuterfn () {document. Write ("Outer function <br/>");FunctionInnerfn () {document. Write ("Inner function <br/>");} Innerfn ();} outerfn ();

 

 

2.1 Great Escape

Javascript allows developers to pass functions like passing any type of data. That is to say, internal functions in javascript can escape defining their external functions.

There are many ways to escape. For example, you can specify an internal function to a global variable:

VaRGlobalvar;FunctionOuterfn () {document. Write ("Outer function <br/>");FunctionInnerfn () {document. Write ("Inner function <br/>");} Globalvar=Innerfn;} outerfn (); globalvar ();

 

When outerfn is called, the global variable globalvar is modified. At this time, its reference is changed to innerfn. After that, globalvar is called and innerfn is called. At this time, calling innerfn directly outside outerfn will still cause errors, because although the internal function can escape by saving the reference in the global variable, however, the name of this function still exists only in the scope of outerfn.

You can also obtain internal function references by returning values from the parent function.

FunctionOuterfn () {document. Write ("Outer function <br/>");FunctionInnerfn () {document. Write ("Inner function <br/>");}ReturnInnerfn ;}VaRFnref =Outerfn (); fnref ();

The global variable is not modified in outerfn, but a reference to innerfn is returned from outerfn. You can obtain this reference by calling outerfn, and the reference can be saved in the variable.

 

The fact that, even if the function scope is left, the internal function can still be called by referencing, meansAs long as the call to internal functions is possible, JavaScript needs to retain the referenced functions. In addition, when Javascript is running, it is necessary to trace all the variables that reference this internal function. Until the last variable is discarded, the Javascript Garbage Collector can release the corresponding memory space (the red part is the key to understanding the closure ).

 

After talking about the closure for a long time,A closure is a function that has the permission to access variables in another function scope.The common way to create a closure is to create another function inside a function, that is, the internal function we mentioned above. So what we just mentioned is not nonsense, but also the closure-related javas_^.

 

1.2 Scope of Variables

Internal functions can also have their own variables, which are restricted to the scope of internal functions:

 Function  Outerfn () {document. Write ( "Outer function <br/>" );  Function Innerfn (){  VaR Innervar = 0 ; Innervar ++ ; Document. Write ( "Inner function \ t" ); Document. Write ( "Innervar =" + innervar + "<br/>" );}  Return  Innerfn ;}  VaR Fnref = Outerfn (); fnref ();  VaR Fnref2 =Outerfn (); fnref2 (); fnref2 (); 

 

Whenever this internal function is called by reference or other means, a new innervar variable is created, followed by 1, and finally displayed.

 
Outer functioninner function innervar = 1 inner function innervar = 1 outer functioninner function innervar = 1 inner function innervar = 1

 

Internal functions can also reference global variables like other functions:

 VaR Globalvar = 0 ;  Function  Outerfn () {document. Write ( "Outer function <br/>" );  Function Innerfn () {globalvar ++ ; Document. Write ( "Inner function \ t" ); Document. Write ( "Globalvar =" + globalvar + "<br/>" );}  Return  Innerfn ;}  VaR Fnref = Outerfn (); fnref ();  VaR Fnref2 = Outerfn (); fnref2 (); fnref2 (); 

 

Now the value of this global variable is continuously increasing every time you call an internal function:

Outer functioninner function globalvar = 1 inner function globalvar = 2 outer functioninner function globalvar = 3 inner function globalvar = 4

 

 

But what if this variable is a local variable of the parent function? Because internal functions reference the scope of the parent function (if you are interested, you can learn about the scope chain and activity object), internal functions can also reference these variables.

 Function  Outerfn (){  VaR Outervar = 0 ; Document. Write ( "Outer function <br/>" );  Function  Innerfn () {outervar ++; Document. Write ( "Inner function \ t" ); Document. Write ( "Outervar =" + outervar + "<br/>" );}  Return  Innerfn ;}  VaR Fnref = Outerfn (); fnref ();  VaR Fnref2 = Outerfn (); fnref2 (); fnref2 (); 

 

This time the results were very interesting and perhaps unexpected.

Outer functioninner function outervar = 1 inner function outervar = 2 outer functioninner function outervar = 1 inner function outervar = 2

We can see the effect of merging in the previous two cases. Calling innerfn through each reference will independently increase outervar. That is to say, the second call of outerfn does not continue to use the value of outervar, but creates and binds a new outervar instance in the scope of the second function call. The two counters are completely irrelevant.

When an internal function is referenced outside its scope, a closure of the internal function is created. In this case, we call neither a local variable of an internal function nor a variable of its parameter as a free variable, and call an environment of an external function as a closed closure. Essentially, if an internal function references a variable in an external function, it is equivalent to authorizing the variable to be delayed. Therefore, when the external function is called, the memory of these variables will not be released (the last value will be saved), and closure still needs to use them.

 

3. Interaction between closures

When multiple internal functions exist, unexpected closures may occur. We define an incremental function. The increment of this function is 2.

 Function  Outerfn (){  VaR Outervar = 0 ; Document. Write ( "Outer function <br/>" );  Function  Innerfn1 () {outervar ++ ; Document. Write ( "Inner function 1 \ t" ); Document. Write ( "Outervar =" + outervar + "<br/>" );}  Function  Innerfn2 () {outervar + = 2 ; Document. Write ( "Inner function 2 \ t" ); Document. Write ( "Outervar =" + outervar + "<br/>" );}  Return {"Fn1": innerfn1, "FN2" : Innerfn2 };}  VaR Fnref = Outerfn (); fnref. fn1 (); fnref. FN2 (); fnref. fn1 ();  VaR Fnref2 = Outerfn (); fnref2.fn1 (); fnref2.fn2 (); fnref2.fn1 (); 

Ing returns the reference of two internal functions. You can call any internal function through the returned reference. The result is as follows:

Outer functioninner function 1 outervar = 1 inner function 2 outervar = 3 inner function 1 outervar = 4 outer functioninner function 1 outervar = 1 inner function 2 outervar = 3 inner function 1 outervar = 4

 

Innerfn1 and innerfn2 reference the same local variable, so they share a closed environment. When innerfn1 is an incremental value of outervar, a new start value of outervar is set for innerfn2, and vice versa. We also seeSubsequent calls to outerfn will also create new instances of these closures and a new closed environment. Essentially, a new object is created, and a free variable is the instance variable of this object, the closure is the instance method of this object.And these variables are private, because they cannot be directly referenced outside the scope of encapsulation, thus ensuring the uniqueness of Object-oriented Data.

 

3. Confused

Now we can look back at the example at the beginning to easily understand why alert 4 is used in the first writing method every time.

For(VaRI = 0; I <spans. length; I ++) {Spans [I]. onclick=Function() {Alert (I );}}

 

The code above will be executed after the page is loaded. When the value of I is 4, the judgment condition is not true and the for loop is executed completely, however, because the onclick method of each span is an internal function at this time, I is referenced by the closure, the memory cannot be destroyed, and the I value will remain 4ProgramIt is recycled only when it is changed or all onclick functions are destroyed (the function is automatically assigned null or the page is uninstalled. In this way, every time we click span, The onclick function will look for the value of I (the scope chain is referenced), check that it is equal to 4, and then alert will give it to us. The second method is to use a function that is executed immediately and create a closure. When the function declaration is placed in parentheses, it becomes an expression, and the brackets are added to the brackets to call the function, when I is passed in, the function is executed immediately, and num stores the value of I each time.

I think everyone knows about the closure as well. If you fully understand it, you need to clarify the execution environment and scope chain of the function. ^_^

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.