简体   繁体   中英

Node.js prototypal inheritance with require

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.

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

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();

You would have to manually extend them in the class that did the requiring.

Extend here meaning "copy the methods and properties from one object to the other"

alternately have helpers require administrator directly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM