How should you inherit from EventEmitter in node?

前端 未结 4 436
无人共我
无人共我 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:36

    function Door() {
        events.EventEmitter.call(this);
    }
    
    Door.prototype.__proto__ = events.EventEmitter.prototype;
    

    In this case using events.EventEmitter.call(this) is like using super in languages which have one. It's actually can be omitted in simple cases, but it will break domain support on current node version and maybe something else in future versions.

    Setting __proto__ just sets up the prototype chain. At can be also done like this:

    Door.prototype = Object.create(events.EventEmitter.prototype);
    

    but in this case you also need to set constructor property manually.

    util.inherits(Door, events.EventEmitter);
    

    This is the idiomatic way of inheriting in node. So you are better to use this. But what it does is basically the same as above.

    function Door() {
    }
    Door.prototype = new events.EventEmitter();
    

    And this is the WRONG way, don't use it! You will end with having events shared between instances in some versions of node.

提交回复
热议问题