Reputation: 1
I have a nested function that re-writes a variable in the parent function. I tried two different invocation syntaxes. Both legal, yet the second one gives undesirable results.
I know scope is determined during definition, but that doesn't seem to help, since both snippets of code seem the same to me.
var countUpFromZero = function() {
var count = 0;
return function() {
return ++count;
};
}();
countUpFromZero(); // Desirable result
var countUpFromZero = function() {
var count = 0;
return function() {
return ++count;
};
};
countUpFromZero()(); //Undesirable result
Upvotes: 0
Views: 40
Reputation: 239682
Your question doesn't say, but I'm assuming the problem is what happens when you call the function more than once. The issue is very simple. Let's change things just a tiny bit, by defining this:
var make_a_counter = function() {
var count = 0;
return function() {
return ++count;
};
};
Now, let's add a variable to your first example:
var counter = make_a_counter();
counter(); // returns 1
counter(); // returns 2
Simple, right? Your second example is equivalent to this:
make_a_counter()(); // returns 1
make_a_counter()(); // returns 1, because you made a *new* counter!
Except in your first example, as provided, you never give make_a_counter
a name, you call it with ()
at the same time as it's defined, so you only can ever make one counter. If you delay calling it, you can make as many of them as you want, and control exactly how long they last.
Upvotes: 4