mithril333221 mithril333221 - 3 months ago 8
Javascript Question

How to chain functions without using prototype?

I have a bunch of useful functions that I have collected during my whole life.

function one(num){
return num+1;
}

function two(num){
return num+2;
}


I can call them with
two(two(one(5)))


But I would prefer to use
(5).one().two().two()


How can I achieve this without using prototype?

I tried to see how underscore chain works, but their code is too intense to understand it

Answer

The dot syntax is reserved for objects. So you can do something like

function MyNumber(n) {
    var internal = Number(n);
    this.one = function() {
        internal += 1;
        // here comes the magic that allows chaining:
        return this;
    }
    // this.two analogous
    this.valueOf = function() {
        return internal;
    }
}

new MyNumber(5).one().two().two().valueOf(); // 10

Or you're going to implement these methods on the prototype of the native Number object/function. That would allow (5).one()...