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

为何其他类调用函数时,Receiver类的字段无法更新?

问题原因与解决方案

问题根源

你遇到的问题是函数上下文丢失:当你把myReceiver.ping作为参数传给Emitter.setEvent时,这个方法脱离了myReceiver实例的上下文。在Emitter.trigger里调用this.event(message)时,ping方法里的this不再指向myReceiver,而是指向Emitter实例(非严格模式下)或者undefined(严格模式下),导致this.messages根本不是myReceiver的数组,自然不会有消息被存入。

无需传递Receiver实例的修复方案

方案1:用bind绑定上下文

直接给ping方法绑定myReceiver作为this,这样不管在哪里调用,this都指向实例:

myEmitter.setEvent(myReceiver.ping.bind(myReceiver));

方案2:箭头函数包裹调用

用箭头函数包裹ping的调用,利用箭头函数继承外层作用域上下文的特性,确保调用时this指向myReceiver:

myEmitter.setEvent((message) => myReceiver.ping(message));

方案3:类内用箭头函数定义方法

在Receiver类里把ping定义为箭头函数类字段,它会自动绑定当前实例的this,传递时不会丢失上下文:

class Receiver {
  constructor() {
    this.messages = [];
  }

  // 箭头函数类字段自动绑定实例this
  ping = (message) => {
    this.messages.push(message);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:42:28