Reputation: 20730
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()));
Upvotes: 1
Views: 180
Reputation: 3142
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.
Upvotes: -1
Reputation: 203231
You should extend/assign EventEmitter.prototype
to your object:
_.assign(parrot, EventEmitter.prototype);
Upvotes: 3