Wikipedia's definition of closures is this:
In computer science, a closure are a function together with a referencing environment for the nonlocal names (free variable s) of that function.
Technically, in JS, each function is a closure, because it always has access to the data defined outside it.
var a=[];
function test ()
{
for (Var i=0;i<6;i++)
{
A[i]=i;
}
}
Test ();
for (Var j in a)
{
document.write (a[j]+ ' </br> ');
}
This is a closure if it's defined by definition, but we can also access a in general.
Since variables defined outside the normal function can be accessed, it is generally only nested functions that we will focus on, and what is often said is that they are nested closures.
As I understand it, the closure of nested functions has two functions:
① guarantees the variable access inside the external function, ensuring that the variable is always present in memory, so that the security of the data can be ensured.
function A () {
var i=0;
Function B () {
i++;//can be modified on the inside of a variable, but also can be returned by return B to I, to ensure that I live in memory, but also can be modified, but also access to I
alert (i);
}
return b;
}
var C = A ();
C ();
② the value of an external variable when solving a block-level domain's function execution is determined by the runtime decision, not by the definition, for example:
var tasks = [];
for (var i = 0; i < 5; i++) {
Tasks[tasks.length] = function () {
document.write (' current cursor are at ' + i + ' </br> ');
};
}
var len = tasks.length;
while (len--) {
Tasks[len] ();
}
var tasks = [];
for (var i = 0; i < 5; i++) {
Tasks[tasks.length] = (function (i) {
return function () {
document.write (' current cursor are at ' + i + ' </br> ');
}
}) (i);
}
var len = tasks.length;
while (len--) {
Tasks[len] ();
}
Result printing
Current cursor was at 5
Current cursor was at 5
Current cursor was at 5
Current cursor was at 5
Current cursor was at 5
Current cursor was at 4
Current cursor was at 3
Current cursor was at 2
Current cursor was at 1
Current cursor was at 0
We see, actually the first function, after running and we expect is not the same, this is the lift effect, so add a closure, the I external variables as parameters passed in, breaking the problem.
This is the two kinds of roles that I've been having now.
JS's closure