Hunq Vux
Hunq Vux

Reputation: 37

Is copying only the prototype of EventEmitter is a good way of inheriting EventEmitter in Nodejs

I've been reading the Nodejs in practice book until I saw this example:

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

function MusicPlayer(track) {
  this.track = track;
  this.playing = false;

  for (var methodName in EventEmitter.prototype) {
    this[methodName] = EventEmitter.prototype[methodName];
  }
}

The author wrote that:"This example might seem a little contrived, but sometimes it really is useful to copy EventEmitter’s properties rather than inherit from it in the usual way. This approach is more akin to a mixin, or multiple inheritance; see this demonstrated in the following listing.". But I just don't get it.

Although the example works like a charm, I can't help figuring it out whether this is a "good practice" to inherit classes in Js or not since the author only copied the prototype property of the EventEmitter class and completely ignore the properties instantiated inside the EventEmitter constructor which wonders me What would happen if I mistakenly invoke a method of the EventEmitter which depends on properties instantiated inside the EventEmitter constructor in order to run?

Suppose that all methods inside prototype of the EventEmitter are independent, is it a "good practice" to inherit classes in Js the way the author did in the example above?

Upvotes: 0

Views: 160

Answers (1)

tbking
tbking

Reputation: 9076

EventEmitter section in Node.js docs give the following example:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

So it is safe to say that this is the recommended approach. The Prototypical inheritance approach recommended by the author is an old way and not encouraged now.

Seems like what the author is trying to say is that it's good to inherit like this when there are multiple inheritance needed which is not allowed in JavaScript.

Upvotes: 2

Related Questions