I've taken a bit of code from How do JavaScript closures work?
I understand how closure works here:
function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp)); // will alert 16
}
bar(10);
}
foo(2);
This will always alert 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo.
What I don't understand is how it works here:
function createArray(array){
var outPut = [];
for (var i = 0; i<array.length; i++){
var inPut = array[i];
outPut.push( function() {alert(inPut + " " + array[i])} );
}
return outPut;
}
function tryArray(){
var finishedArray = createArray([1, 2, 3, 4]);
for (var i = 0; i < finishedArray.length; i++) {
finishedArray[i]();
}
}
tryArray();
It logs 4 undifined
four times.
What I expected to happen was it to log. 1 1 2 2 3 3 4 4
Why didn't this happen???