You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Builder模式下无需build方法自动返回链式调用最终值

实现链式调用最后一步返回具体值的几种方案

方案1:显式调用取值方法(最简洁可靠)

这是最直观的实现方式,保留链式调用的核心逻辑,最后通过专门的方法获取具体值,同时不影响后续继续调用实例方法:

class MyClass {
  constructor() {
    this.value = 0;
  }

  plus(amount) {
    this.value += amount;
    return this;
  }

  minus(amount) {
    this.value -= amount;
    return this;
  }

  val() {
    return this.value;
  }
}

// 使用示例
const num = new MyClass().plus(10).minus(3).val(); // 7
// 继续调用方法也完全可行
const instance = new MyClass().plus(5);
const anotherNum = instance.minus(2).val(); // 3

方案2:利用valueOf()自动转换值

借助JS的类型转换机制,给类添加valueOf()方法,当链式调用结果被用于数值运算、类型转换时自动返回具体值,平时仍保持实例可继续调用方法:

class MyClass {
  constructor() {
    this.value = 0;
  }

  plus(amount) {
    this.value += amount;
    return this;
  }

  minus(amount) {
    this.value -= amount;
    return this;
  }

  // 触发数值转换时返回具体值
  valueOf() {
    return this.value;
  }

  // 触发字符串转换时返回对应字符串
  toString() {
    return String(this.value);
  }
}

// 使用示例
const chain = new MyClass().plus(7).minus(2); // chain是MyClass实例
console.log(+chain); // 5(通过+号触发valueOf)
console.log(chain - 0); // 5
console.log(String(chain)); // "5"

// 继续调用方法不影响
chain.plus(3);
console.log(+chain); // 8

方案3:用代理包装实现隐式取值

通过Proxy包装实例,让方法调用后返回代理对象,当需要获取值时通过类型转换自动返回,同时保留链式调用能力:

class MyClass {
  constructor() {
    this.value = 0;
  }

  #createChainProxy() {
    return new Proxy(this, {
      get(target, prop) {
        // 若访问的是实例方法,调用后返回代理以维持链式
        if (typeof target[prop] === 'function' && prop !== 'valueOf') {
          return (...args) => {
            target[prop](...args);
            return this.#createChainProxy();
          };
        }
        return Reflect.get(target, prop);
      },
      // 转换为原始值时返回具体数值
      getOwnPropertyDescriptor(target, prop) {
        if (prop === 'valueOf') {
          return { value: () => target.value };
        }
        return Reflect.getOwnPropertyDescriptor(target, prop);
      }
    });
  }

  static init() {
    return new MyClass().#createChainProxy();
  }

  plus(amount) {
    this.value += amount;
  }

  minus(amount) {
    this.value -= amount;
  }
}

// 使用示例
const result = +MyClass.init().plus(6).minus(1); // 5
// 继续链式调用
const chain = MyClass.init().plus(4);
const anotherResult = +chain.minus(2); // 2

内容的提问来源于stack exchange,提问作者noiseymur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:06:26