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

标签 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;

最佳答案

首先我需要说 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.");

关于javascript - 局部变量在 javascript 的回调函数中变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548439/

相关文章:

javascript - 检查是否设置了 Cookie,然后加载页面,否则重定向页面

循环内的javascript settimeout并重复

javascript - 返回带有格式化日期的额外列

javascript - 范围问题 - 此函数是否形成闭包 - JavaScript?

javascript - ng 类表达式 : merge condition and class name

javascript - 配置文件: JS vs INI

ruby-on-rails - 一个模型的两个关系上的 ActiveRecord 命名范围

javascript - 更改 javascript 对象内的范围

node.js - 确定 MongoClient 实例是否已连接

node.js - LDAP JS 身份验证出错