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

时间:2016-11-11 12:53:01

标签: javascript node.js scope callback prototype

我是一个试图编写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;

1 个答案:

答案 0 :(得分:1)

首先,我需要说Teemu是正确的。 Arrow Functions这是我自己不熟悉的问题。如果您希望在不使用Arrow Functions的情况下看到另一种完成相同操作的方法,请查看下面的代码段。

这段代码我稍后会改为Immediately-Invoked Function Expression (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.");