局部变量在javascript的回调函数中变为未定义

jia chen

我是一位试图编写JavaScript的Java程序员,似乎无法掌握调用回调时范围的变化。

下面的bot.sendmessage无法运行。错误日志显示“ undefined.bot.sendMessage(formId,resp)”

"use strict";

function Handlers() {
    this.bot = undefined;

    this.registerHandler = (bot)=>{
        this.bot = bot;
        bot.on('message', this._messageCallback);
        bot.on('inline_query', this._inlineCallback)
    }
}

Handlers.prototype = {

    _messageCallback: (msg) => {
        console.log("New Outline Request from: chat=" + msg.chat.id + ", uid=" + msg.from.id);
       
        var fromId = msg.from.id;
        var resp = "Hello there";
        this.bot.sendMessage(fromId, resp);
    },
    _inlineCallback: (msg) => {
        console.log("New Inline Request from: uid=" + msg.from.id);
        /*
         TODO::
         check if user is in data base if not log new entry;
         */
    }
};

module.exports = Handlers;

暴风雪

首先我要说泰穆是正确的。这是我自己不熟悉的Arrow Functions的问题如果您想了解一种无需使用箭头功能即可完成同一件事的替代方法,请查看下面的代码片段。

稍后,我会将这段代码更改为立即调用的函数表达式(IIFE),但这是我的个人编程习惯。我在这里不知道您的确切用例。

"use strict";

/**
 * I'm assuming you have this elsewhere?
 * If not I have added it to show how to do it
 */
function bot(){
   /* ... */
}

bot.prototype = {
    sendMessage: function(formId,resp){
        console.log("Form: "+formId+" | Message: "+resp);
    }
};
/**
 * End of my addition
 */

function Handlers() {
    this.bot = new bot();
    
    /* ... */
}

Handlers.prototype = {

    _messageCallback: function(msg){
        /* ... */
        var fromId = "fakeid123";
        var resp = msg;
        this.bot.sendMessage(fromId, resp);
    },
    _inlineCallback: function(msg){
        /* ... */
    }
};

var myModule= new Handlers();
myModule._messageCallback("Here is my test msg.");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档