Sam
Sam

Reputation: 3559

node.js util.inherits vs new

On the Node.js documentation we can see :

var util = require("util");
var events = require("events");

function MyStream() {
    events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);

var stream = new MyStream();

Is it the same as :

function MyStream2() {
}
//MyStream2 = new events.EventEmitter; WRONG. Thank you @Esailija
MyStream2.prototype = new events.EventEmitter;

var stream2 = new MyStream2();

Thank you :)

Upvotes: 2

Views: 934

Answers (1)

Esailija
Esailija

Reputation: 140220

If we edit your code to be working, that is:

MyStream2.prototype = new events.EventEmitter;

There will be still some differences:

  • In your version, MyStream2.prototype.constructor === events.EventEmitter, with inherits, MyStream2.prototype.constructor === MyStream2

  • Your version invokes events.EventEmitter constructor which could have side effects., whereas inherits uses Object.create which doesn't invoke the constructor function.

  • Not related to the differences between chaining prototypes, but your version doesn't call parent constructor when the child constructor is called. So it should still have function MyStream2() { events.EventEmitter.call(this); } to properly establish initial state when the child constructor is called.

Upvotes: 7

Related Questions