I'm trying to make a function that holds state but is called with foo().
Is it possible?
I believe this is what you want:
var foo = (function () {
var state = 0;
return function () {
return state++;
};
})();
Or, following the Wikipedia example:
var makeAccumulator = function (n) {
return function (x) {
n += x;
return n;
};
};
var acc = makeAccumulator(2);
alert(acc(2)); // 4
alert(acc(3)); // 7
JavaScript is one of those languages that has, IMHO, excellent support for functions as first class citizens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With