How should you inherit from EventEmitter in node?

前端 未结 4 437
无人共我
无人共我 2020-12-09 20:55

I was reading over this small article to understand inheriting from EventEmitter, but I\'m a little confused.

He does this:

function Doo         


        
4条回答
  •  借酒劲吻你
    2020-12-09 21:30

    The Node v6.3.1 documentation states about util.inherits(constructor, superConstructor):

    Usage of util.inherits() is discouraged. Please use the ES6 class and extends keywords to get language level inheritance support. Also note that the two styles are semantically incompatible.


    The following code shows how to inherit from EventEmitter with Typescript:

    import { EventEmitter } from "events"
    
    class Person extends EventEmitter {
        constructor(public name: string) {
            super()
        }
    }
    
    let person = new Person("Bob")
    person.on("speak", function (said: string) {
        console.log(`${this.name} said: ${said}`)
    })
    person.emit("speak", "'hello'") // prints "Bob said: 'hello'"
    

    The previous code will transpile into the following ES6 code:

    "use strict";
    const events = require("events");
    class Person extends events.EventEmitter {
        constructor(name) {
            super();
            this.name = name;
        }
    }
    let person = new Person("Bob");
    person.on("speak", function (said) { console.log(`${this.name} said: ${said}`); });
    person.emit("speak", "'hello'");
    

提交回复
热议问题