mignz
mignz

Reputation: 3908

Running prototype functions after function

I'm trying to learn a bit more about javascript prototypes (I guess that's what this is called). I saw some NodeJS modules with functions being called like this: something.funcA().funcB().funcC(); and I am trying to reproduce it. How can I do it and how's it called?

This is what I got so far from trying:

var total = { t: 0 };

module.exports.calculate = function() {
    var calc = {};

    calc.result = function result() {
        return total.t;
    }

    calc.add = function add(num) {
        total.t += num;
        return this;
    }

    calc.sub = function sub(num) {
        total.t -= num;
        return this;
    }

    return calc;
};

When I call the function:

calc = require('../helpers/calculate');

// 5 - 1 + 3 = 7
calc.calculate().add(5).sub(1);
calc.calculate().add(3);

console.log(calc.calculate().result());

Running add() works but not when I run sub() after add():

TypeError: Cannot read property 'sub' of undefined

Upvotes: 3

Views: 188

Answers (1)

SLaks
SLaks

Reputation: 887275

add(5).sub(1) calls sub() on the object returned by add().

Since add() doesn't return anything, that won't work.

You probably want to return this.

Upvotes: 3

Related Questions