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

TypeScript调用动态函数保留类上下文解决私有成员访问报错问题

报错根因

你在names对象中直接存储this.sendToto方法引用时,丢失了方法原本的this上下文绑定。当你在send方法中调用这个存储的函数时,this不再指向myClass的实例,而TypeScript的私有字段(#开头的字段)只能在声明它的类的实例上下文中访问,上下文错误就触发了这个报错。

可用解决方案

所有方案均不需要手动注入helloService实例,按需选择即可:

方案1:将sendToto改为箭头函数绑定上下文

箭头函数的this在定义时就会绑定到当前类实例,不会随调用位置变化,改完后完整代码如下:

export class HelloService {
  sayHello(name: string) {
    console.log('hello', name)
  }
}
export class myClass {
  readonly #helloService: HelloService;

  names: { [index: string]: Array<Function> } = {
    toto: [this.sendToto]
  }

  constructor() {
    this.#helloService = new HelloService();
  }

  send(name: string) {
    this.names[name][0]('someparams')
  }
  // 改为箭头函数,自动绑定实例this
  sendToto = (params: string) => {
    this.#helloService.sayHello(params)
  }
}
(new myClass()).send('toto');

方案2:存储方法引用时主动绑定this

在把sendToto存入names数组时,用bind方法把this绑定到当前实例,其他代码不需要改动:

names: { [index: string]: Array<Function> } = {
  toto: [this.sendToto.bind(this)]
}

方案3:调用函数时手动指定上下文

在send方法中调用存储的函数时,用call方法指定this为当前类实例,只需要修改调用的一行代码即可:

send(name: string) {
  this.names[name][0].call(this, 'someparams')
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:36:04