我有以下代码:
const myObj = {
reply(text: string, options?: Bot.SendMessageOptions)
{
return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options });
},
replyMd(text: string, options?: Bot.SendMessageOptions)
{
return this.reply(text, { parse_mode: "Markdown" });
}
};
但是,当我调用replyMd
时,this
是未定义的。为什么?
考虑这个例子:
const foo = {
bar() {
console.log(this)
}
}
调用foo.bar()
日志
Object {bar: function bar()}
但是
const {bar} = foo
bar()
日志undefined
有关详细解释,请参阅MDN的这篇文章。
在函数内部,this的值取决于函数的方式呼叫。[…]当函数作为对象的方法调用时,它设置为方法调用的对象。