NodeJS EventEmitter在类中不会被调用

当我注册一个函数作为一个事件,在所述函数内的发射不会被调用。 它自己的function被称为(通过日志testing)。 现在,当我使用方法2注册事件时,它工作。 为什么是这样?

方法1(不叫事件):

"use strict"; const EventEmitter = require("events"); class DiscordBot extends EventEmitter{ constructor(key){ super(); } startBot(){ var self = this; this.bot.on("ready",self.botReady); } botReady(){ var self = this; self.emit("Bot_Ready"); console.log("TESD"); } } 

方法2(作品):

 "use strict"; const EventEmitter = require("events"); class DiscordBot extends EventEmitter{ constructor(key){ super(); } startBot(){ var self = this; this.bot.on("ready",function () { self.botReady(); }); } botReady(){ var self = this; self.emit("Bot_Ready"); console.log("TESD"); } } 

寄存器:

  bot.on("Bot_Ready", function(){ console.log('this happens '); }); 

这将创build一个closures :

 this.bot.on("ready",function () { self.botReady(); }); 

方法1不:

  startBot(){ var self = this; this.bot.on("ready",self.botReady); } 

从上面的MDN链接:

封闭是一种特殊的对象,它结合了两个方面:一个function和创buildfunction的环境。 环境由创build闭包时在范围内的任何局部variables组成。

这是另一个很好的链接,可能有助于解释:

JavaScriptclosures如何工作?

注意这个部分:

在JavaScript中,如果您在另一个函数中使用了function关键字,那么您正在创build一个闭包。

“也许你失去了上下文,你需要使用箭头函数this.bot.on(”ready“,()=> this.botReady());” – @yurzui

奇迹般有效。