I recently ran into an issue at work in which, at least according to my knowledge of JavaScript, I got back an impossible result. I'm hoping someone can explain whats going on here and why the actual results differ from my expected results.
Expected results in console
id: a , x: 1
id: b , x: 1
id: c , x: 1
Actual results in console
id: c , x: 1
id: c , x: 2
id: c , x: 3
Code
function MyClass(id)
{
var x = 0;
return function()
{
return function()
{
x += 1;
console.log("id: ", id, ", x: ", x);
}
}
}
function DoStuff(id)
{
var q = MyClass(id);
response_callback = q();
setTimeout(function(){ response_callback(); }, 50);
}
DoStuff("a");
DoStuff("b");
DoStuff("c");