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

如何实现类任意方法调用时自动递增count计数,避免冗余代码?

实现类方法调用自动计数的方案

以下提供两种常用的实现方案,均不需要在每个业务方法内手动添加计数逻辑:


方案1:使用Proxy代理实例(无侵入式,无需修改原类代码)

该方案完全不需要改动原有类的代码,仅在创建实例时用Proxy做一层包装即可实现计数能力,灵活性最高。

class Foo{
  constructor(){
    this.count = 0;
  }
  method1() { console.log('执行method1') }
  method2() { console.log('执行method2') }
  method3() { console.log('执行method3') }
}

// 封装可生成带计数能力实例的工厂函数
function createCountedInstance(Clazz) {
  const instance = new Clazz();
  return new Proxy(instance, {
    get(target, prop) {
      const value = target[prop];
      // 仅对类方法做包装,跳过构造函数、count属性等非方法项
      if (typeof value === 'function' && prop !== 'constructor') {
        return function(...args) {
          target.count++;
          // 保留原方法的this指向和返回值
          return value.apply(target, args);
        }
      }
      return value;
    }
  })
}

// 使用示例
const foo = createCountedInstance(Foo);
foo.method1(); // 输出:执行method1
foo.method2(); // 输出:执行method2
console.log(foo.count); // 输出:2

方案特点:

  • 适配任意类,完全不侵入原有业务代码
  • 可按需选择是否给实例开启计数能力,不需要的实例可以直接正常创建

方案2:类构造函数内批量改造方法(所有实例默认带计数)

如果希望该类的所有实例默认自带方法调用计数能力,可以直接在类的构造函数内批量改写原型方法,仅需修改一次构造函数即可,后续新增类方法也会自动适配计数逻辑。

class Foo{
  constructor(){
    this.count = 0;
    const proto = Object.getPrototypeOf(this);
    // 过滤出类原型上的所有方法
    const methodNames = Object.getOwnPropertyNames(proto).filter(prop => 
      typeof proto[prop] === 'function' && prop !== 'constructor'
    );
    // 批量给方法添加计数逻辑
    methodNames.forEach(name => {
      const originalMethod = proto[name];
      this[name] = (...args) => {
        this.count++;
        return originalMethod.apply(this, args);
      }
    })
  }
  method1() { console.log('执行method1') }
  method2() { console.log('执行method2') }
  method3() { console.log('执行method3') }
}

// 使用示例
const foo = new Foo();
foo.method1();
foo.method3();
console.log(foo.count); // 输出:2

方案特点:

  • 所有实例默认自带计数能力,无需额外的实例创建封装逻辑
  • 后续新增类方法自动支持计数,不需要额外修改代码

注意:如果类方法使用箭头函数语法声明,这类方法会绑定到实例本身而非类原型,方案2需要调整遍历逻辑改为遍历实例自身属性即可,Proxy方案不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:06:03