Reputation: 10323
Why does it not count, my output is always 1 in the console. I am new to closures and I must be missing something simple? Here is the code from the jsbin:
var counterFunc = function()
{
var count = 0;
var incCount = function()
{
count = count + 1;
return count;
};
return incCount();
};
var myCounter = counterFunc;
console.log(myCounter());
console.log(myCounter());
Upvotes: 0
Views: 39
Reputation: 339786
You should be returning the inner function itself, not the result of calling it
You therefore need to replace return incCount()
with:
return incCount;
You subsequently need to directly invoke counterFunc()
when you declare myCounter
:
var myCounter = counterFunc(); // myCounter is now the closure
Only then will myCounter
be assigned a reference to the inner function, that happens to hold a "closure" over the local variable count
.
Upvotes: 2
Reputation: 664327
By returning incCount()
- the result of the invocation - from your counterFunc
, you're not really creating a closure function. You want to return a function, and invoke the counterFunc()
to create it:
var counterFunc = function() {
var count = 0;
var incCount = function() {
count = count + 1;
return count;
};
return incCount ;
// ^
};
var myCounter = counterFunc();
// ^^
console.log(myCounter());
console.log(myCounter());
Upvotes: 4