views:

316

answers:

2

I'm trying to make a function that holds state but is called with foo().
Is it possible?

+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
it returns undefined twice.
the_drow
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
Thanks. The foo example. I commented before the second example.
the_drow
The foo example didn't return a value. I've added a return so that it should behave as expected.
Prestaul
Good idea Prestaul, thanks.
Ionuț G. Stan
+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