mithril333221 mithril333221 - 1 year ago 79
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

But I would prefer to use

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 Source

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

function MyNumber(n) {
    var internal = Number(n); = 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()...

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