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

使用Array.find时如何避免丢失this指向?

问题原因

你遇到的报错是因为:将History方法作为commands数组对象的method属性存储后,调用该方法时,this的指向不再是类实例,而是指向了commands里的单个command对象,自然无法访问类的status属性。

解决方法

方法1:定义时绑定this

在commands数组中,用bind把类实例的this绑定到History方法上,确保方法执行时this始终指向类实例:

module.exports = new class {
   status = { COMMAND_SUCCESS: 1 }

   commands = [{
        name: "history",
        method: this.History.bind(this) // 绑定类实例的this
   }];

   commandsNames = ["history"];

   async Execute(command)
   {
        var commandParts = command.toLowerCase().split(" ");
        var commandFound = this.commands.find(command => command.name === commandParts[0]);
        return commandFound["method"]();
   }

   async History()
   {
      return this.status.COMMAND_SUCCESS; 
   }
}

方法2:用箭头函数定义类方法

箭头函数的this遵循词法作用域,会自动继承外层类实例的this,无需额外绑定:

module.exports = new class {
   status = { COMMAND_SUCCESS: 1 }

   commands = [{
        name: "history",
        method: this.History
   }];

   commandsNames = ["history"];

   async Execute(command)
   {
        var commandParts = command.toLowerCase().split(" ");
        var commandFound = this.commands.find(command => command.name === commandParts[0]);
        return commandFound["method"]();
   }

   // 改为箭头函数形式
   History = async () => {
      return this.status.COMMAND_SUCCESS; 
   }
}

方法3:调用方法时绑定this

在Execute方法中调用method时,用call把当前类实例的this传入,强制指定方法的this指向:

module.exports = new class {
   status = { COMMAND_SUCCESS: 1 }

   commands = [{
        name: "history",
        method: this.History
   }];

   commandsNames = ["history"];

   async Execute(command)
   {
        var commandParts = command.toLowerCase().split(" ");
        var commandFound = this.commands.find(command => command.name === commandParts[0]);
        // 调用时用call绑定类实例的this
        return commandFound["method"].call(this);
   }

   async History()
   {
      return this.status.COMMAND_SUCCESS; 
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:36:03