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

JavaScript随机执行类方法时内部this为undefined修复方案

问题根因

类内部默认运行在严格模式,当你将类方法从实例上提取出来存入数组时,方法和实例的绑定关系会断开,直接调用脱离实例的方法时,this会指向undefined。
另外原代码存在两处语法错误,会直接导致代码无法运行:

  • 构造函数名拼写错误:construstor 正确写法为 constructor
  • 方法定义漏写参数括号:async main_method 正确写法为 async main_method()
修复方法

以下两种方案任选其一即可,均适配ES私有方法(#开头)的场景:

方案1:调用时手动绑定上下文

执行方法时通过.call()指定this指向当前实例,无需额外修改构造函数:

class test {
  constructor(smth) {
    this.smth = smth
  }
  async main_method() {
    const methodList = [this.#method1, this.#method2, this.#method3].sort(() => Math.random() - 0.5);
    for (const func of methodList) {
      // 绑定当前实例为this上下文后再执行
      await func.call(this, this.smth);
    }
  }
  async #method1(smth) {
    // 此处this可正常访问类实例
  }
  async #method2(smth) {
    // 此处this可正常访问类实例
  }
  async #method3(smth) {
    // 此处this可正常访问类实例
  }
}

方案2:构造函数内提前绑定

在构造函数中提前将私有方法的this固定到当前实例,后续调用无需额外处理:

class test {
  constructor(smth) {
    this.smth = smth;
    // 提前绑定所有私有方法的上下文
    this.#method1 = this.#method1.bind(this);
    this.#method2 = this.#method2.bind(this);
    this.#method3 = this.#method3.bind(this);
  }
  async main_method() {
    const methodList = [this.#method1, this.#method2, this.#method3].sort(() => Math.random() - 0.5);
    for (const func of methodList) {
      await func(this.smth);
    }
  }
  async #method1(smth) {
    // 此处this可正常访问类实例
  }
  async #method2(smth) {
    // 此处this可正常访问类实例
  }
  async #method3(smth) {
    // 此处this可正常访问类实例
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:06:29