Possible Duplicate:
Javascript closure?
This has probably been asked before, but...
If I want a list of functions
var funs = [
function(){ console.log(1); },
function(){ console.log(2); },
function(){ console.log(3); },
function(){ console.log(4); },
function(){ console.log(5); } ]
it would seem that one could make it by something like:
var funs = [];
for(var i=1; i <= 5; i++){
funs.push(function(){ console.log(i) };
}
Which doesn't work, as the variable i
is a single variable bound to all the functions, so that
funs[0](); funs[1](); funs[2](); funs[3](); funs[4]();
outputs
6
6
6
6
6
not
1
2
3
4
5
This isn't the output I want. I guess I need to force javascript to bind a copy of the value of i
at the time the function is created, instead of closing with the reference for i
. How would I do this?