I am looking at this function
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp));
}
}
var bar = foo(2); // bar is now a closure.
bar(10);
when I run it, the variables get the following values
x = 2,
y = 10
tmp = 3.
Now I see that in foo(2) x is passed as 2. So its understandable that x is getting the value of 2. But then bar(10) is assigning a value of 0 to y. Hows that? I am confused on how does the receiving function know that 10 is the value for y assigned by bar(10)
foo(2)returns an anonymous function which accepts one parameter (y). As you’re settingbarto be the return value offoo(2),barbecomes a reference to that anonymous function.So, when you call
bar(10)you’re calling the anonymous functionfooreturns, and so10is being set to the parametery.