无法读取未定义的属性消息.(在这个消息中)



我正在尝试为我的机器人制作一个CommandHandler。所以我使用
command.js

module.exports = class CommandHandler{
constructor(message, args){
this.message = message;
this.args = args;
}
ping(){
this.message.send("pong");
}
}

在index.js中,我只是像一样使用它

const CommandHandler = require("./command");
/*
The Client on message and other initialization
then,
*/
let Command = new CommandHandler(message, args);
let Execute = Command["ping"];
Execute();

我犯了这个错误无法读取未定义的'messge'
并且调试器指向this.message.reply()

发生这种情况是因为函数丢失了上下文。您可以通过Command.ping()Command实例上调用它,也可以通过以下方式绑定上下文。

let Execute = Command["ping"].bind(Command);
Execute();

最新更新