Callback Definition Closure Issue
Solution 1:
The issue stems from me not understanding that function(){}
on its own is a definition and so is "a"
and {}
. Since these are definitions then the definition scope of the function passed is appropriately placed where it is and the world makes sense again.
Solution 2:
In first case, it is forming a closure and has access to the variable "b" but in second case it does not form a closure at all. If you put a debugger just before the cb() inside the function, you will notice that there is no closure formed and the reason of that being the callback function is suplied to the function as an argument and it becomes local to that function which does not have any knowledge of the variable b.
Think of it as two different functions, one in which it has a local variable "b" and in other no local variable but we are trying to access it which throws the reference error.
Post a Comment for "Callback Definition Closure Issue"