What is JavaScript closure?

Source: Internet
Author: User

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 following code

Copy codeThe Code is as follows: <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>

Copy codeThe Code is as follows: $ (document). ready (function (){
Var spans = $ ("# divTest span ");
For (var I = 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.

Copy codeThe Code is as follows: var spans2 = $ ("# divTest2 span ");
$ (Document). ready (function (){
For (var I = 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:

Copy codeThe Code is as follows: function outerFn (){
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:

Copy codeThe Code is as follows: function outerFn (){
Document. write ("Outer function <br/> ");
Function innerFn (){
Document. write ("Inner function <br/> ");
}
}
InnerFn ();

However, if innerFn is called within outerFn, the operation can be successful:

Copy codeThe Code is as follows: function outerFn (){
Document. write ("Outer function <br/> ");
Function innerFn (){
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:

Copy codeThe Code is as follows: var globalVar;
Function outerFn (){
Document. write ("Outer function <br/> ");
Function innerFn (){
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.

Copy codeThe Code is as follows: function outerFn (){
Document. write ("Outer function <br/> ");
Function innerFn (){
Document. write ("Inner function <br/> ");
}
Return innerFn;
}
Var fnRef = 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 the internal function can still be called by referencing even if the function scope is left exists means that JavaScript needs to retain the referenced function as long as the internal function is called. 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, it is related to the closure. The closure refers to a function with the permission to access the variables of another function scope. A common way to create a closure is to create another function within a function, it is the internal function we mentioned above, so what we just talked about 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:

Copy codeThe Code is as follows: 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 ();
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.

Copy codeThe Code is as follows: Outer function
Inner function innerVar = 1
Inner function innerVar = 1
Outer function
Inner function innerVar = 1
Inner function innerVar = 1

Internal functions can also reference global variables like other functions:

Copy codeCode: 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 ();
FnRef ();
Var fnRef2 = outerFn ();
FnRef2 ();
FnRef2 ();

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

Copy codeThe Code is as follows: Outer function
Inner function globalVar = 1
Inner function globalVar = 2
Outer function
Inner 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.

Copy codeThe Code is as follows: 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 ();
FnRef ();
Var fnRef2 = outerFn ();
FnRef2 ();
FnRef2 ();

This time the results were very interesting and perhaps unexpected.

Copy codeThe Code is as follows: Outer function
Inner function outerVar = 1
Inner function outerVar = 2
Outer function
Inner 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.

Copy codeThe Code is as follows: 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:

Copy codeThe Code is as follows: Outer function
Inner function 1 outerVar = 1
Inner function 2 outerVar = 3
Inner function 1 outerVar = 4
Outer function
Inner 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 can also see that subsequent calls to outerFn will also create new instances of these closures, and will also create a new closed environment, essentially creating a new object, free variables are the instance variables of this object, and closures are the instance methods of this object, and these variables are also private, because they cannot be directly referenced outside the scopes that encapsulate them, this ensures the uniqueness of object-oriented data.

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

Copy codeThe Code is as follows: for (var I = 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 always be 4, it will not be recycled until the program changes it or all the 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.