Node.js Question

util.inherits - alternative or workaround

I am a n00b in node, and find

very useful, except for the fact that it seems to replace the entire prototype of the original object. For instance:

var myClass = function(name){
this._name = name;

myClass.prototype = {

util.inherits(myClass, require('events').EventEmitter);

seems to erase my original prototype.

That brings me two inconveniences:

1 - I have to declare add properties to my prototype after calling

var myClass = function(name){
this._name = name;

util.inherits(myClass, require('events').EventEmitter);

myClass.prototype.prop1 = function(){...};
myClass.prototype.prop2 = function(){...};

and, most important, i think i cannot inherit from two or more different classes.

Can anyone explain to me why this makes sense and what would be a good way to work around this?


Answer Source

As of node version 5.0.0, util.inherits has been changed to support the behaviour you are looking for using the setPrototypeOf method:


function FirstBase(firstBaseProp){
    this.firstBaseProp = firstBaseProp;

FirstBase.prototype.getFirstBaseProp = function(){
    return this.firstBaseProp;

module.exports = FirstBase;


var FirstBase = require('./FirstBase.js'),
    util = require('util');

function SecondBase(firstBaseProp, secondBaseProp){
    this.secondBaseProp = secondBaseProp;
    SecondBase.super_.apply(this, arguments);

SecondBase.prototype.getSecondBaseProp = function(){
    return this.secondBaseProp;

util.inherits(SecondBase, FirstBase);

module.exports = SecondBase;


var SecondBase = require('./SecondBase.js'),
    util = require('util');

function ThirdBase(firstBaseProp, secondBaseProp, thirdBaseProp){
    this.thirdBaseProp = thirdBaseProp;
    ThirdBase.super_.apply(this, arguments);

ThirdBase.prototype.getThirdBase = function(){
    return this.thirdBaseProp;

util.inherits(ThirdBase, SecondBase);

module.exports = ThirdBase;


var ThirdBase = require('./ThirdBase.js');

var instance = new ThirdBase('first', 'second', 'third');

// With node < 5.0.0 (Object.create)
console.log(instance.getFirstBaseProp()); // first
console.log(instance.getSecondBaseProp()); // undefined
console.log(instance.getThirdBase()); // undefined

// With node >= 5.0.0 (Object.setPrototypeOf)
console.log(instance.getFirstBaseProp()); // first
console.log(instance.getSecondBaseProp()); // second
console.log(instance.getThirdBase()); // third

If you're running an older version of node that supports setPrototypeOf (0.12.x does), you can just export util.inherits and use it as an internal utility function.