Possible Duplicate:
Javascript closure inside loops - simple practical example
Javascript: closure of loop?
so I would like the results to be 1,2,3 instead of 3,3,3. How do I set the context/scope so that the jobs are using the correctly scoped "i"?
function buildJobs(list) {
var jobs = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
jobs.push( function() {alert(item)} );
}
return jobs;
}
function testJobs() {
var jobs = buildJobs([1,2,3]);
for (var j = 0; j < jobs.length; j++) {
jobs[j]();
}
}