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

如何实现函数及父类函数执行完毕后单次同步回调(附示例)

解决方案

要实现你想要的事件监听器风格功能——在子类和父类的目标方法都执行完毕后同步触发一次回调,且只需注册一次,我们可以通过给父类添加钩子管理机制来实现。下面是完整的实现代码:

class Parent {
  // 私有字段存储回调钩子
  #afterHooks = [];
  // 标记回调是否已执行,确保仅触发一次
  #hookTriggered = false;

  doSomething() {
    console.log("Parent doSomething");
  }

  // 注册回调的方法,只需调用一次
  onAfterExecute(callback) {
    this.#afterHooks.push(callback);
  }

  // 私有方法:执行所有回调(仅一次)
  #executeHooks() {
    if (!this.#hookTriggered) {
      this.#afterHooks.forEach(callback => callback());
      this.#hookTriggered = true;
    }
  }

  // 供子类调用的公共方法,触发钩子
  finalizeExecution() {
    this.#executeHooks();
  }
}

class Child extends Parent {
  doSomething() {
    // 先执行父类的方法
    super.doSomething();
    // 执行子类自己的逻辑
    console.log("Child doSomething");
    // 所有逻辑执行完毕后,触发父类的钩子
    super.finalizeExecution();
  }
}

// 使用示例
const childInstance = new Child();

// 仅注册一次回调
childInstance.onAfterExecute(() => {
  console.log("I'm not a callback that runs multiple times!");
});

// 第一次调用:父类方法→子类方法→回调
childInstance.doSomething();
// 第二次调用:仅执行父类和子类方法,回调不再触发
childInstance.doSomething();

方案适配性说明

这个实现完美匹配你的所有需求:

  • 回调仅执行一次:通过私有字段#hookTriggered标记回调是否已触发,第一次执行后就会阻止后续触发。
  • 回调同步执行:#executeHooks直接同步调用所有回调函数,没有任何异步逻辑。
  • 类方法按指定顺序调用:子类doSomething先调用super.doSomething()执行父类逻辑,再执行自身逻辑,最后触发回调,完全符合顺序要求。
  • 回调仅需指定一次:通过onAfterExecute注册一次后,后续调用doSomething无需再传递回调。

运行结果

控制台会输出:

Parent doSomething
Child doSomething
I'm not a callback that runs multiple times!
Parent doSomething
Child doSomething

可以看到,回调内容只在第一次调用doSomething时打印,完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:52:29