我正在学习如何在nodejs中使用事件发射器和继承。我得到错误:
TypeError: this.on is not a function
我代码:
const EventEmitter = require('events')
const Emitter = function () {
EventEmitter.call(this)
this.on('event',value => {
console.log('Event emitted',value)
})
}
const myEmitter = new Emitter()
我做错了什么?
使用上面的代码,您实际上并没有继承EventEmitter
。我只是使用一个实际的类extends
它:
const EventEmitter = require('events')
class Emitter extends EventEmitter {
constructor() {
super();
this.on('event', value => {
console.log('Event emitted', value)
});
}
}
const myEmitter = new Emitter();
myEmitter.emit('event', 'hello'); // logs 'Event emitted hello' to the console.