I recently ran into a problem in which, at least in my knowledge of JavaScript, I got an impossible result. I hope someone can explain what is happening here and why the actual results are different from my expected results.
Expected Console Results
id: a , x: 1 id: b , x: 1 id: c , x: 1
Actual results in the console
id: c , x: 1 id: c , x: 2 id: c , x: 3
The 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");
javascript scope asynchronous
B keyes
source share