Jonathan
Jonathan

Reputation: 543

Multiple inheritance with node.js utils.inherits?

Hi I'm new to node and I'm trying to build an MVC app. For the controllers and models I was able to use utils.inherits to create base and sub-classes. For views, I'd like to create 3 levels: base, html/json, module. At each level there is a function called construct that needs to be called when an instance is created, and calling it at the top should chain back through each level.

Base view:

function Base_view( ) {
    this._response = null;
};

Base_view.prototype.construct = function( res ) {
    this._response = res;
};

Html view:

var util = require( 'util' ),
    Base_view = require( './view' );

function Html_view( ) {
    Base_view.apply( this, arguments );
}

util.inherits( Html_view, Base_view );

Html_view.prototype.construct = function( res, name ) {
    this.constructor.super_.prototype.construct.apply( this, arguments );
};

Module view:

var util = require( 'util' ),
    Html_view = require( './../base/html' );

function Main_view( ) {
    Html_view.apply( this, arguments );
}

util.inherits( Main_view, Html_view );

Main_view.prototype.construct = function( ) {
    this.constructor.super_.prototype.construct.apply( this, arguments );
};

This line in the module view produces an undefined error:

this.constructor.super_.prototype.construct.apply( this, arguments );

If I only subclass once it correctly calls the parent classes construct method. How do I use it to extend multiple times?

In this post: util.inherits - alternative or workaround there is a modified utils.inherits method that looks like its supposed to do it but I can't figure out how to use it? I've tried requiring both classes in module and putting all three as params.

Thanks!

Upvotes: 2

Views: 4354

Answers (1)

Jonathan
Jonathan

Reputation: 543

Got it working by removing my attempt at adding a faux callable constructor and using the func def as the constructor. Ignore the util require, it's just a wrapper to include some standard util functions and a few of my own. All it does is call the built in method.

/controllers/base/view.js:

function Base_view( res ) {
    this._response = res;
};

/controllers/base/html.js:

var util = require( '../../helpers/util' ),
    Base_view = require( './view' );

function Html_view( res, name ) {
    Base_view.apply( this, arguments );
    this._name = name;
};

util.inherits( Html_view, Base_view );

/controllers/main/html.js:

var util = require( '../../helpers/util' ),
    Html_view = require( './../base/html' );

function Main_view( res, name ) {
    Html_view.apply( this, arguments );
};

util.inherits( Main_view, Html_view );

Upvotes: 6

Related Questions