How do I create method chaining functionality similar to jQuery
in JavaScript
. For eg. I have a main function where I can add different methods to it like add, subtract, multiply, divide, while main function taking one param.
Main(5).add(3).subtract(2).multiply(4).divide(6)
or
Main(10).subtract(5).add(5).divide(6)
It can be anything.
I was trying to put methods in an object in the return statement of the parent function, but it didn't work.
function main(a) {
return {
sum: function (b) {
return a b;
},
substract: function (c) {
return a - c;
},
};
}
Please help
CodePudding user response:
Change your code to:
function Main(a) {
this.value = a;
}
Main.prototype.sum = function (a) {
this.value = a;
return this;
}
Main.prototype.subtract = function (a) {
this.value -= a;
return this;
}
Usage:
let var1 = new Main(5).sum(3).subtract(2); // var1.value = 6
CodePudding user response:
You could return an object of functions and store the result. At the end return only the value by taking a getter function.
function chain(value) {
const methods = {
add: v => {
value = v;
return methods;
},
substract: v => {
value -= v;
return methods;
},
get value() { return value; }
}
return methods;
}
console.log(chain(3).add(4).substract(5).value);
CodePudding user response:
Maintain a local variable n
, perform the math on it, and then return this
from each method.
function main (n = 0) {
return {
add: function(x) {
n = n x;
return this;
},
subtract: function(x) {
n = n - x;
return this;
},
total: function () {
return n;
}
};
}
const total = main(12)
.add(2)
.subtract(1)
.total();
console.log(total);