I'm trying to make a function that holds state but is called with foo().
Is it possible?
views:
316answers:
2
+12
A:
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.
Ionuț G. Stan
2009-07-14 10:53:05
it returns undefined twice.
the_drow
2009-07-14 11:02:22
Which "it". The foo() example does indeed return undefined. It was just as an example. The accumulator example should work as expected. I've added a simple use case.
Ionuț G. Stan
2009-07-14 11:05:05
Thanks. The foo example. I commented before the second example.
the_drow
2009-07-14 11:12:08
The foo example didn't return a value. I've added a return so that it should behave as expected.
Prestaul
2009-07-14 13:38:15
Good idea Prestaul, thanks.
Ionuț G. Stan
2009-07-14 13:49:46
+1
A:
Since Javascript functions are first-class objects, this is the way to do it:
var state = 0; var myFunctor = function() { alert('I functored: ' + state++);};
The "state" variable will be available to the myFunctor function in its local closure. (Global in this example). The other answers to this question have the more sophisticated examples.
There's no equivalent to just "implementing operator ()" on some existing object, though.
Gavin
2009-09-19 18:33:49