the_drow the_drow - 1 year ago 49
Javascript Question

Is it possible to make a functor in JavaScript?

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

Is it possible?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download