Yalamber Yalamber - 6 months ago 27
Node.js Question

How to implement inheritance in node.js modules?

I am in process of writing nodejs app. It is based on expressjs. I am confused on doing inheritance in nodejs modules. What i am trying to do is create a model base class, let's say my_model.js.

module.exports = function my_model(){
my_model.fromID = function(){
//do query here
}
}


Now i want to use those methods in my_model in my other model class. let's say user_model.js
How do i inherit my_model in user_model?

Answer

in base_model:

function BaseModel() { /* ... */ }

BaseModel.prototype.fromID = function () { /* ... */ };

module.exports = BaseModel;

in user_model:

var BaseModel = require('relative/or/absolute/path/to/base_model');

function UserModel() {
    UserModel.super_.apply(this, arguments);
}

UserModel.super_ = BaseModel;

UserModel.prototype = Object.create(BaseModel.prototype, {
    constructor: {
        value: UserModel,
        enumerable: false
    }
});

UserModel.prototype.yourFunction = function () { /* ... */ };

module.exports = UserModel;

Instead of using Object.create() directly, you can also use util.inherits, so your user_model becomes:

var BaseModel = require('relative/or/absolute/path/to/base_model'),
    util = require('util');

function UserModel() {
    BaseModel.apply(this, arguments);
}

util.inherits(UserModel, BaseModel);

UserModel.prototype.yourFunction = function () { /* ... */ };

module.exports = UserModel;