创建可重复使用的链函数 javascript

Create reusable chain function javascript

我试图创建可重复使用的链接函数,但我被卡住了。常用方法 c.plus(5).plus(2).execute() 工作正常,但我不知道如何使它像下面这样可重用。你知道怎么做吗?

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

您当前函数的问题在于,当您调用 plus() 时,您正在修改原始对象 c 中的 i

相反,每次调用 plus(arg) 时 return 一个新的 chain 对象,将 arg 添加到 i 的当前值。

顺便说一句,在 javascript 中习惯使用 TitleCase 来命名构造函数。通常 chain 会是 Chain。仅供参考。

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