1. A simple example
First from a classic error, there are several div on the page, we want to bind them to a onclick method, so we have the following code
Copy Code code 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 Code code as follows:
$ (document). Ready (function () {
var spans = $ ("#divTest span");
for (var i = 0; i < spans.length; i++) {
Spans[i].onclick = function () {
alert (i);
}
}
});
Very simple function But it happens to be wrong, each alert out of the value is 4, simple modification is good
Copy Code code 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 function
Let's start with some basic knowledge about the internal functions. An intrinsic function is a function defined in another function. For example:
Copy Code code as follows:
function Outerfn () {
FUNCTIONINNERFN () {}
}
INNERFN is an internal function that is wrapped in a OUTERFN scope. This means that calling INNERFN inside Outerfn is valid, and calling INNERFN outside of OUTERFN is not valid. The following code causes a JavaScript error:
Copy Code code as follows:
function Outerfn () {
document.write ("Outer function<br/>");
function Innerfn () {
document.write ("Inner function<br/>");
}
}
INNERFN ();
However, if you call INNERFN inside OUTERFN, you can run successfully:
Copy Code code as follows:
function Outerfn () {
document.write ("Outer function<br/>");
function Innerfn () {
document.write ("Inner function<br/>");
}
INNERFN ();
}
OUTERFN ();
2.1 The Great Escape
JavaScript allows developers to pass functions like any type of data, meaning that internal functions in JavaScript can escape the definition of their external functions.
There are many ways to escape, for example, you can assign an intrinsic function to a global variable:
Copy Code code 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 invoked, the global variable Globalvar is modified, when its reference becomes INNERFN, and then calls Globalvar and calls INNERFN. Calling INNERFN directly outside the OUTERFN will still result in an error, because the intrinsic function, although it escaped by saving the reference in a global variable, is still the name of the function in the scope of the OUTERFN.
You can also get an internal function reference by the return value of the parent function
Copy Code code as follows:
function Outerfn () {
document.write ("Outer function<br/>");
function Innerfn () {
document.write ("Inner function<br/>");
}
return INNERFN;
}
var fnref = OUTERFN ();
Fnref ();
Instead of modifying the global variable inside the OUTERFN, a reference to INNERFN is returned from the OUTERFN. This reference can be obtained by invoking OUTERFN, and the reference may be saved in a variable.
The fact that the internal function can be invoked by reference even if it leaves the function scope means that JavaScript needs to retain the referenced function whenever there is a possibility of invoking an intrinsic function. and the JavaScript runtime needs to track all the variables that refer to the internal function until the last variable is discarded, and the JavaScript garbage collector frees up the appropriate memory space (the red part is the key to understanding the closure).
After half a day, I finally had a relationship with the closure, a closure is a function that has permission to access a variable of another function, and the common way to create a closure is to create another function inside a function, which is the internal function we're talking about, so it's not nonsense, it's a closure-related ^_^
Scope of 1.2 variables
Internal functions can also have their own variables, which are limited to the scope of the internal function:
Copy Code code 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 intrinsic function is invoked by reference or otherwise, a new Innervar variable is created, followed by 1, and the final display
Copy Code code 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 refer to global variables like other functions:
Copy Code code as follows:
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 ();
The value of this global variable is continuously incremented each time the internal function is invoked:
Copy Code code 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 the variable is a local variable of the parent function? Because intrinsic functions refer to the scope of the parent function (interested in understanding the scope chain and the knowledge of the active object), internal functions can also refer to these variables
Copy Code code 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 result is very interesting, perhaps or to our surprise
Copy Code code as follows:
Outer function
Inner function Outervar = 1
Inner function Outervar = 2
Outer function
Inner function Outervar = 1
Inner function Outervar = 2
What we see is the effect of the previous two cases, the INNERFN will be incremented independently by each reference invocation Outervar. This means that the second call OUTERFN does not continue to follow the Outervar value, but instead creates and binds a new Outervar instance in the scope of the second function call, with two counters completely unrelated.
When an intrinsic function is referenced outside the scope that defines it, a closure of the intrinsic function is created. In this case, we say that neither the internal function local variable nor its parameter is a free variable, and that the calling environment of the external function is a closed-closure environment. Essentially, if an intrinsic function references a variable in an external function, it is tantamount to authorizing the variable to be deferred. Therefore, when external function calls are complete, the memory of these variables is not freed (the last value is saved), and closures still need to be used.
3. The interaction between closures
When multiple internal functions are present, unexpected closures are likely to occur. We define an increment function, the increment of this function is 2
Copy Code code 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 ();
We map a reference that returns two internal functions that can be invoked by the returned reference, resulting in the following:
Copy Code code 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 refer to the same local variable, so they share a closed environment. When innerFn1 for Outervar increments for a while, long absence innerFn2 set a new threshold for Outervar, and vice versa. We also see that subsequent calls to OUTERFN also create new instances of these closures. It also creates a new enclosing environment, essentially creating a new object in which the free variable is the instance variable of the object, and the closure is the instance method of the object, and the variables are private, Because these variables cannot be directly referenced outside the scope that encapsulates them, this ensures the exclusivity of object-oriented data.
4. FAQ
Now we can look back at the example at the beginning and it's easy to see why the first way of writing is alert 4 at a time.
Copy Code code as follows:
for (var i = 0; i < spans.length; i++) {
Spans[i].onclick = function () {
alert (i);
}
}
The above code executes when the page is loaded, when I has a value of 4, the judgment condition does not set, the For loop executes, but because each span's OnClick method is at this time an intrinsic function, so I is closed the package reference, the memory cannot be destroyed, I the value will keep 4, It will not be reclaimed until the program changes it or if all the onclick functions are destroyed (by actively assigning the function to null or the page is unloaded). So every time we click on the span, the onclick function looks at the value of I (the scope chain is the reference), 4, and then alert us. The second way is to use an immediately executed function and create a layer of closure, the function declaration is placed in parentheses into the expression, followed by parentheses and brackets is called, and then the I when the argument passed, the function immediately execute, NUM save each time I value.
This pass down presumably everyone also like me, on the closure of some understanding of it, of course, fully understand the words need to the function of the execution environment and scope of the chain to understand ^_^