Search code examples
javascriptprototype

Currying function constructor


I'd like to know if it is possible to achieve this in javascript:

function Hello() { }

Hello.prototype.echo = function echo() {
  return 'Hello ' + this.firstname + '!';
};

// execute the curryed new function
console.log(new Hello()('firstname').echo())

Is it possible to curry var o = new Class()(param1)(param2)(...) ?

Thank you in advance for your help.


Solution

  • Using the answer of georg with an array of the properties and a counter for assigning an arbitrary count of properties.

    function Hello() {
        var args = ['firstname', 'lastname'],
            counter = 0,
            self = function (val) {
                self[args[counter++]] = val;
                return self;
            };
        Object.setPrototypeOf(self, Hello.prototype);
        return self;
    }
    
    Hello.prototype.echo = function echo() {
        return 'Hello ' + this.firstname + ' ' + (this.lastname || '') + '!';
    };
    
    console.log(new Hello()('Bob').echo());
    console.log(new Hello()('Marie')('Curie').echo());