0

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

1
  • its the same instance what do expect the result to be? Commented Mar 10, 2018 at 11:21

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Happy to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.