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

如何将回调函数传递到类的init初始化函数中

实现方案

基础实现逻辑

你只需要改造Person类的构造函数,让它支持接收回调参数,再在init方法的对应位置执行回调即可。以下是遍历完nums数组后执行回调的示例:

class Person {
  // 构造函数增加callback参数,默认赋值空函数避免不传时报错
  constructor(callback = () => {}) {
    this.nums = [1, 2, 3];
    // 将回调挂载到实例属性,方便init方法调用
    this.userCallback = callback;
    this.init();
  }
  init() {
    this.nums.forEach(num => {
      console.log(num);
    });
    // 执行传入的回调函数
    this.userCallback();
  }
}

function test() {
  console.log('test')
}

// 实例化时直接把test函数作为参数传入即可
const person = new Person(test);

执行上述代码会依次输出:1、2、3、test。


自定义执行时机

如果你需要调整回调的执行位置,直接修改init方法里的调用位置即可:

  • 比如每打印一个数值就执行一次回调:
init() {
  this.nums.forEach(num => {
    console.log(num);
    this.userCallback();
  });
}

执行后输出顺序为:1、test、2、test、3、test。


注意事项

如果回调函数内需要访问Person实例的属性,注意绑定正确的this指向,两种常见处理方式:

  1. 实例化时用bind绑定:
function test() {
  console.log(this.nums) // 可以访问实例的nums属性
}
const person = new Person(test.bind(person));
  1. 直接传入箭头函数:
const person = new Person(() => {
  console.log(person.nums)
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:45:03