jia chen
jia chen

Reputation: 760

Local variable becomes undefined in callback function in javascript

Im a java programmer trying to write javascript cant seem to grasp how scope changes when callbacks are called.

bot.sendmessage below failes to run. Error log says "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;

Upvotes: 0

Views: 826

Answers (1)

Blizzardengle
Blizzardengle

Reputation: 1071

First I need to say Teemu is correct. This is an issue with Arrow Functions which I myself am unfamiliar with. If you would like to see an alternative way of acomplishing the same thing without using Arrow Functions take a look at the snippet below.

This code I would change later to be an Immediately-Invoked Function Expression (IIFE) but that is my personal programming habits. I don't know your exact use case here.

"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.");

Upvotes: 1

Related Questions