在对象文字中引用“ this”

时间:2018-11-26 17:27:45

标签: javascript typescript

我有以下代码:

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是不确定的。为什么?

1 个答案:

答案 0 :(得分:0)

考虑以下示例:

const foo = {
  bar() {
    console.log(this)
  }
}

调用foo.bar()日志

Object {bar: function bar()}

但是

const {bar} = foo
bar()

日志undefined

有关详细说明,请参见this MDN article

  

在函数内部,此值取决于函数的方式   叫。 [...]当函数被调用为对象的方法时,其   设置为调用该方法的对象。