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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With