简体   繁体   中英

Node.js inheritance of modules

I have trouble with inheritance in node.js. I followed patterns from stackoverflows existing threads, but my code is still not working like it should.

Lets start with just two items, first 'base.js' :

function Base() {
    this.type = 'empty';
}

Base.prototype.getType = function () {
    return this.type;
}

module.exports = Base;

Then I have my 'second.js' file and it should inherit from Base

var Base = require('./base.js'), util = require('util');

function Second() {
    Base.apply(this, arguments);
}

util.inherits(Second, Base);


Second.prototype.getData = function () {
    return 12;
}

module.exports = Second;

In my app.js I call

var second = new require('./second.js');
console.log(second.getType());

And thats throwing error 'getType is undefined'. However, when I put all this in a single file (ex. app.js) it all works fine. Can you point out what's wrong in my code or suggest a better way of doing it?

Thanks!

In your app.js you need to first require constructor, and then construct new instance:

var Second = require('./second.js');
var second = new Second();

console.log(second.getType());

alternatively you could also do:

var second = new (require('./second.js'));
console.log(second.getType());

But in any case, you need to first require and only after apply new operator. It has to do with operator precedence , new operator has very high priority.

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