Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js prototypal inheritance with require

Node.js prototypal inheritance with require

Problem

I have a problem with inheritance of two functions in node.js when i use require functions.

Here is my case:

function administrators () {
    this.user = 'bob';
}
administrators.prototype.print_user = function () {
    console.log(this.user);
}

/*******/


function helper() {}

helper.prototype = new administrators();

helper.prototype.change_administrator = function() {
    this.user = 'john';

}

var h = new helper();

h.print_user();
h.change_administrator();
h.print_user();

As you can see here I have two functions:

  • administrations just has user variable and print_user function.
  • helpers inherits everything from administrators and then we add change_administrator which changes this.use declared in administrators().

Here is the question:

I want to have this functions (administrators and helper) in separated files, for example: administrators.js and helper.js.

Then I want to include these two files in index.js with require, and inherit administrators variables and functions to helper like I did in the example above.

P.S. I was looking for similar questions but there is nothing about that kind of inheritance.

Problem courtesy of: GuramK

Solution

You need to require Administrators from within the helpers.js file.

administrators.js

function administrators () {
    this.user = 'bob';
}
administrators.prototype.print_user = function () {
    console.log(this.user);
}

module.exports = administrators;

helpers.js

var administrators = require('./administrators');

function helper() {}

helper.prototype = new administrators();

helper.prototype.change_administrator = function() {
    this.user = 'john';
};

module.exports = helper;

index.js

var helper = require('./helpers');

var h = new helper();

h.print_user();
h.change_administrator();
h.print_user();
Solution courtesy of: Alex

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js prototypal inheritance with require

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×