Scope and Asynchronous JavaScript

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"); 
+6
javascript scope asynchronous
source share
1 answer
 response_callback = q(); 

It. You have not declared response_callback in any scope, so it is implicitly in the global scope ...

This means that you rewrite it every time you call DoStuff() . You think you have three different functions captured and called, but there is only one ...

  var response_callback = q(); // should set you back on track 

Of course, the way you have it structured right now distracts MyClass ability to return a function that returns a function. You can really write:

 function DoStuff(id) { var q = MyClass(id); // ... do other strange and horrible things with q ... setTimeout(q(), 50); } 

... and see the same results without unnecessary closure.

+6
source share

All Articles