TypeError:this.sendHandshake不是一个函数

我试图为nodejs&socket.io游戏创build一个简单的类(包装)。

module.exports = class client { constructor(socket) { this.socket = socket; this.createEvents(); } createEvents() { console.log('creating events'); this.socket.on('handshake', this.onHandshake); this.socket.on('disconnect', this.onDisconnect); } sendHandshake() { // <------------ sendHandshake is there? console.log('sending handshake'); this.socket.emit('handshake'); } onHandshake() { console.log('handshake received'); this.sendHandshake(); // <----- TypeError: this.sendHandshake is not a function } onDisconnect() { console.log('client disconnected'); } } 

它应该给我这个输出

 creating events handshake received sending handshake 

但相反,它给了我这个错误

 creating events handshake received TypeError: this.sendHandshake is not a function 

当您传递一个函数时,它不会自动绑定到拥有函数的对象。 一个更简单的例子是:

 const EventEmitter = require('events'); class client { constructor() { this.ev = new EventEmitter; this.ev.on('handshake', this.onHandshake); this.ev.emit('handshake'); } onHandshake() { console.log(this); // EventEmitter } } 

相反,您必须将函数绑定到client ,只需使用this.onHandshake.bind(this)() => this.onHandshake() 。 前者明确地将其绑定。 后者将this词汇结合起来,也就是说,无论this在定义的函数中如何。


我还会指出,你通过发出handshake来回应handshake – 不知道这是有意的还是需要的。