我是一名试图编写 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/