I am a bit perplexed when i saw a piece of code and trying to understand why calling it anonymous keeps the value of total and not otherwise.
var adder = function (total) {
// the following function is returned
// and assigned to adder
var inner_function = function (summand) {
total += summand;
alert(total);
}
return inner_function;
}(0) // <- we call the annonymous function
// and assign the returned function to adder
adder(2); // -> 2
adder(3); // -> 5
What I don't understand is if i don't invoke anonymous function, it doesn't keep the value of total. why? without (0) if i am calling adder(2) shouldn't it behave like the first call where it keeps the value of total and then assign internal_function to variable adder?
It says in the blog that "And when you call adder, that is the inner_function, it has access to total due to Lexical Scoping, even though the function that had the total. total itself was declared in the scope of a function that has returned a long time ago." http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/
just trying to understand how anonymous works in this case