1

I see this all the time:

Parrot.prototype.__proto__ = EventEmitter.prototype;

With this, each time you construct a new parrot, it can squawk.

However, supposing I construct an object with functions and don't intend to create multiple instances:

var parrot = {
  squawk: function(whatYouSaid){
    this.emit("SQUAWK!!!!", whatYouSaid);
  }
}

How would I make this extend EventEmitter? I tried this, and it didn't work:

_.extend(parrot, (new EventEmitter()));
dthree
  • 19,847
  • 14
  • 77
  • 106

2 Answers2

3

You should extend/assign EventEmitter.prototype to your object:

_.assign(parrot, EventEmitter.prototype);
robertklep
  • 198,204
  • 35
  • 394
  • 381
-1

util.inherits is the native api for doing inheritance in NodeJS.

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

function Parrot(){
  EventEmitter.call(this);
  ...
}

util.inherits(Parrot, EventEmitter);

var parrot = new Parrot();

parrot.on('SQUAWK!!!!', whatYouSaid);

parrot.emit('SQUAWK!!!!', 'I said this!');

I made a demo of different ways of doing inheritance: https://github.com/razvanz/nodejs-inheritance-demo.

Razvan
  • 3,017
  • 1
  • 26
  • 35