简体   繁体   English

Nodejs - this.on 不是 function 事件发射器 object inheritance

[英]Nodejs - this.on is not a function event emitter object inheritance

I'm learning how to use event emitter and inheritance in nodejs.我正在学习如何在 nodejs 中使用事件发射器和 inheritance。 I get the error:我收到错误:

TypeError: this.on is not a function

My code:我的代码:

const EventEmitter = require('events')

const Emitter = function () {
    EventEmitter.call(this)

    this.on('event',value => {
        console.log('Event emitted',value)
    })
}

const myEmitter = new Emitter()

What I'm doing wrong?我做错了什么?

With above code you're not actually inheriting from EventEmitter .使用上面的代码,您实际上并没有继承自EventEmitter I'd just use an actual class that extends it:我只是使用一个实际的 class 来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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM