在对象文字中引用"this"



我有以下代码:

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的值取决于函数的方式呼叫。[…]当函数作为对象的方法调用时,它设置为方法调用的对象。

相关内容

最新更新