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

将类方法传入函数调用时出现this指向错误的技术求助

问题原因与解决方案

这个报错的核心是类方法传递时丢失了this指向:当你把cubeClass.changeColour单独传给change函数时,方法内部的this不再指向cubeClass实例,而是变成了undefined(严格模式下),所以访问this.white会抛出属性未定义的错误。

解决方法有三种,任选其一即可:


1. 用bind绑定实例到方法

传递方法时,通过bind强制把this绑定到原实例:

class Cube {
  constructor() {
    this.white = "white";
  }
  changeColour() {
    this.white = "red";
    console.log(this.white);
  }
}

const cubeClass = new Cube();
function change(method) {
  method();
}

// 修正后的调用
change(cubeClass.changeColour.bind(cubeClass));

2. 用箭头函数包裹方法调用

通过箭头函数的词法作用域保留this指向,调用时直接指向原实例:

// 其他代码不变
change(() => cubeClass.changeColour());

3. 在类中用箭头函数定义方法

类内部用箭头函数定义方法,会自动把this绑定到实例,后续传递方法时不会丢失指向:

class Cube {
  constructor() {
    this.white = "white";
  }
  // 箭头函数定义方法,this永久绑定实例
  changeColour = () => {
    this.white = "red";
    console.log(this.white);
  }
}

const cubeClass = new Cube();
function change(method) {
  method();
}

// 直接传递即可
change(cubeClass.changeColour);

内容的提问来源于stack exchange,提问作者The Hacking Gamer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:34:59