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 andprint_user
function.helpers
inherits everything fromadministrators
and then we addchange_administrator
which changesthis.use
declared inadministrators()
.
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
精彩评论