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]();
}
}
Wrap the inner function with a another function that’s immediately executed and receives
ias an argument:You’re now closing over the
ithat is local to the wrapper function, which is a different variable in each iteration. (In your original configuration each inner function was closing over the same variable (whose value was3by the time any of the functions ever executed).)