开发者

Node.js prototypal inheritance with require

开发者 https://www.devze.com 2023-04-05 08:34 出处:网络
I have a problem with inheritance of two functions in node.js when i use require functions. Here is my case:

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开发者_JS百科 did in the example above.

P.S. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号