Question

In this pattern:

Function ConstrA () {
    EventEmitter.call(this);
}
util.inherits(ConstrA, EventEmitter);

var obj = new ConstrA();

ConstrA and obj would have its own prototype chain without the call to util.inherits.

Does util.inherits create a second prototype chain or replace the current one for ConstrA or does it just add the properties (both own and inherited) of the prototype chain of EventEmitter to the prototype of ConstrA?

Was it helpful?

Solution

util.inherits overwrites the prototype of the constructor with an object whose prototype is set to the prototype of the constructor you are inheriting from.

If you want to inherit your prototype from another object, then add additional methods to your custom constructor's prototype, you would need to make sure you call util.inherits on your custom constructor prior to defining any other prototype methods on it.

The node.js source for util.inherits is surprising simple. take a look for yourself!

https://github.com/joyent/node/blob/490d5ab7808aedb998d1f4f933bf3de748758f62/lib/util.js#L631

Then you can read the MDN docs for Object.Create to fill in the remaining gaps in understanding.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top