The anonymous functions use(share) the same key and value variables from the outer scope. When the for is over, the values they use are key2 value2, not the values they had when the functions were defined.
for (var key in dataList) // definition of key
{
var value = dataList[key]; // definition of value
jobList.push(
function (next)
{
console.log(key + ' : ' + value); // uses key and value from the outer scope
}
);
}
(jobList[0])(); // key and value are key2 value2 after for, so they are printed
(jobList[1])(); // same
The solution is to create a closure in which key and value are local:
for (var key in dataList) // definition of key
{
var value = dataList[key]; // definition of value
jobList.push(
function(k,v){ // k,v local copies of key and value
return function (next)
{
console.log(k + ' : ' + v); // uses local copies, created one for each iteration
}
}(key,value); // immediately execute the outer anonymous function, it just creates a local scope
);
}