function box() {
var arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = function () {
return i;
}
}
return arr;
}
var b = box();
for (var i = 0; i < 5; i++) {
alert(b[i]);
}
After box() is executed, why are the values in arr[0] to arr[4] all function () { return i;}
Why are they not: function () {return 0;} , function () {return 1;}. . .
Because the closure can only obtain the last value of any variable in the function, which here refers to the variable i, the box() function returns a function array after execution, and each i in the array refers to the same A variable i. Note that box() returns a function! So {return i} inside is just a statement within the function and has not been executed yet, so of course {return i} remains unchanged. Because it refers to the same external i, when the box() function returns, the value of the external variable i is 5. At this time, each return refers to the same variable object that saves the variable i, so if the internal The function in arr[], the final value of i inside each function is 5.
Because the scope chain associated with the closure is "live" . And they share the variable i , rather than assigning its own separate copy of the value of each bound variable. They just reference i, The value of i at each stage will not be saved.
Reference Book: The Definitive Guide to JavaScript Section 8.6.
In the example, the function in the for loop is only assigned a value and not executed, so the value of i is only obtained when the function in the array is executed. At this time, i only has the value at the end of the loop. No closure is used upstairs, just an immediate The executed anonymous function gets the value of i for each loop;
Method: 1. Use ES6 let to replace var
function box() {
2. Use closure
function box() {
. The word "closure" comes from the combination of a block of code to be executed (because the free variables are contained within the block, these free variables and the objects they refer to are not released) and the binding provided for the free variables. Computing environment (scope) ---Baidu Encyclopedia
means
This is a code block. Its function is only to reference i, so that holding i will prevent i from being released. What we save is only this code block. Before this code block is run, it does not know that i is Whatever it is, it will only look for i when it is running, so you can output all your arr, and all the output should be 5
i
is calculated only when
is called.When calling these functions,
for
has ended, so the value when takingi
is5