var i = 0,
j = 0;
var funcs = [];
for (i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function() { // and store them in funcs
console.log("My value: " + i); // each should log its value.
};
}
for (j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
/* This is the result you may expect.
My value: 0
My value: 1
My value: 2
But instead, it will output like this:
My value: 3
My value: 3
My value: 3
*/
//Wyjaśnienie: anonimowa funkcja utworzona w pętli posiada referencje do wartości utworzonej w innym scopie. To tak samo jak:
function outside() {
var val = 0;
return function() {
console.log('My value: ', val + 1);
}
}
outside()() // 1
outside()() // 1
//Dopiero przypisanie wyniku funkcji do nowej zmiennej, tworzy nowy kontekst dla zwróconej funkcji i trzyma jej status bez zmian wewnątrz oryginalnej f-cji outside.
var newVal = outside()
newVal() //1
newVal() //2
outside()() // 1