Startec
Startec

Reputation: 13206

Why use util.inherits and .call for inheritance in Node.js

I am wondering why, when creating a new stream class in node, I need to use both call and util.inherits

For instance, in the following code, which is used to create a readable stream, I have to use both:

var Readable = require('stream').Readable;
var util = require('util');


var MyStream = function (options) {
    Readable.call(this, options)
}

util.inherits(MyStream, Readable); //Hasn't this already inherited all methods from Readable via "call"

var stream = new MyStream();

It seems to be that Readable.call is calling the constructor from Readable and therefore the util.inherits is unnecessary.

Upvotes: 2

Views: 490

Answers (1)

Mike
Mike

Reputation: 4091

util.inherits will merge the prototype from Readable into MyStream. Both this prototype merge and the constructor call are required for a more complete sense of inheritance.

The constructor call Readable.call( ... ) will just run through the constructor of Readable, likely initializing some variables and maybe do some initial setup.

The prototype merge util.inherits(MyStream, Readable); will take the prototype methods on Readable and stick them onto any future instances of MyStream.

So without the constructor call you don't get that initial setup, and without the prototype merge you don't get the methods. From that you can see why it is required to both both steps.

Upvotes: 4

Related Questions