I trying to create reusable chaining function, but I'm stuck. Common way c.plus(5).plus(2).execute()
work fine, but I have no idea how to make this reusable like below. Do you have any idea how to do this?
function chain() {
this.i = 0;
this.plus = (x) => {
this.i = this.i + x;
return this;
};
this.execute = () => console.log(this.i);
}
const c = new chain();
const c1 = c.plus(5);
c1.plus(2).execute(); // 7
c1.execute();// 7 instead of 5
The problem with your current function is that when you call plus()
, you are modifying i
in the original object c
.
Instead, return a new chain
object each time you call plus(arg)
, adding arg
to the current value of i
.
BTW it is customary in javascript to use TitleCase
to name constructors. Usually chain
would be Chain
. FYI.
function Chain() {
this.i = 0;
this.plus = (x) => {
let c = new Chain();
c.i = this.i + x;
return c;
};
this.execute = () => console.log(this.i);
}
const c = new Chain();
const c1 = c.plus(5);
c1.plus(2).execute(); // 7
c1.execute();// 7 instead of 5
c.plus(2).plus(10).execute(); // 12