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

JavaScript类内函数出现this未定义TypeError,求无需传onError的解决方案

问题分析与解决方案

首先咱们来拆解一下为什么会出现TypeError: this is undefined:
当你在initialize方法里给class2绑定错误回调时,那个普通的回调函数(如果是用function声明的)在被Class2内部触发执行时,它的this指向已经不是Class1的实例了——普通函数的this是由调用它的上下文决定的,这里Class2调用回调时,this要么指向Class2实例,要么在严格模式下直接是undefined,自然找不到onError方法。

接下来给你几种不用把onError传给initialize的解决办法:

方法1:用箭头函数定义回调

箭头函数不会创建自己的this,它会继承外层作用域的this(也就是Class1的实例),这样就能直接访问this.onError:

class Class1{
 constructor(props) {
  this.class2 = Class2(props.publicKey);
  this.onError = props.onError;
 }

 initialize() {
  // 用箭头函数作为回调
  this.class2.on('error', (event) => {
    this.onError(event.error.message);
  });
 }
}

方法2:在构造函数里绑定回调的this

提前把处理错误的方法的this绑定到Class1实例,这样不管这个方法被谁调用,this都不会变:

class Class1{
 constructor(props) {
  this.class2 = Class2(props.publicKey);
  this.onError = props.onError;
  // 绑定handleError的this到当前实例
  this.handleError = this.handleError.bind(this);
 }

 handleError(event) {
  this.onError(event.error.message);
 }

 initialize() {
  this.class2.on('error', this.handleError);
 }
}

方法3:用闭包保存this

在initialize里先把当前实例的this存成一个变量(比如self),回调里用这个变量代替this:

class Class1{
 constructor(props) {
  this.class2 = Class2(props.publicKey);
  this.onError = props.onError;
 }

 initialize() {
  const self = this;
  this.class2.on('error', function(event) {
    self.onError(event.error.message);
  });
 }
}

这三种方法都不需要修改initialize的参数,完全在Class1内部解决了this指向的问题,你可以根据自己的代码风格选一种用就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:19:06