Reputation: 37
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!
Upvotes: 1
Views: 43
Reputation: 193261
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.
Upvotes: 1