jeffreyveon jeffreyveon - 4 months ago 14x
Node.js Question

Node.js - inheriting from EventEmitter

I see this pattern in quite a few Node.js libraries:

Master.prototype.__proto__ = EventEmitter.prototype;

(source here)

Can someone please explain to me with an example, why this is such a common pattern and when it's handy?


As the comment above that code says, it will make Master inherit from EventEmitter.prototype, so you can use instances of that 'class' to emit and listen to events.

For example you could now do:

masterInstance = new Master();

masterInstance.on('an_event', function () {
  console.log('an event has happened');

// trigger the event

Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':

var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);