gremo
gremo

Reputation: 48439

Is events.EventEmitter.call(this) required when creating a custom EventEmitter?

There are a lot of example not using events.EventEmitter.call(this) in custom event emitter constructors, while other are using it (official documentation):

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

var MyEmitter = function () {
    events.EventEmitter.call(this);
};

util.inherits(MyEmitter, events.EventEmitter);

MyEmitter.prototype.write = function () {
    this.emit('tick');
};

With my basic understandings of JavaScript I don't know if I need it. Is the call necessary to to initialization stuff inside the EventEmitter?

Upvotes: 5

Views: 2107

Answers (1)

SLaks
SLaks

Reputation: 887887

Yes, it is.

Before Node 0.10, it wouldn't break if you forget that.

Now, it will:

The EventEmitter constructor initializes various properties now. It still works fine as an OOP inheritance parent, but you have to do inheritance properly. The Broken-Style JS inheritance pattern will not work when extending the EventEmitter class. This inheritance style was never supported, but prior to 0.10, it did not actually break.

Upvotes: 5

Related Questions