簡體   English   中英

局部變量在javascript的回調函數中變為未定義

[英]Local variable becomes undefined in callback function in javascript

我是一位嘗試編寫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."); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM