Reputation: 204
I have inherited a class from another JS, and added few prototype function over Parent functions. When i create a new instance of child, i want to call the constructor of parent. Please suggest a way.
Parent
function Parent() { .. }
Parent.prototype.fn1 = function(){};
exports.create = function() {
return (new Parent());
};
Child
var parent = require('parent');
Child.prototype = frisby.create();
function Child() { .. }
Child.prototype.fn2 = function(){};
exports.create = function() {
return (new Child());
};
Upvotes: 1
Views: 3484
Reputation: 1274
You can use module util. Look simple example:
var util = require('util');
function Parent(foo) {
console.log('Constructor: -> foo: ' + foo);
}
Parent.prototype.init = function (bar) {
console.log('Init: Parent -> bar: ' + bar);
};
function Child(foo) {
Child.super_.apply(this, arguments);
console.log('Constructor: Child');
}
util.inherits(Child, Parent);
Child.prototype.init = function () {
Child.super_.prototype.init.apply(this, arguments);
console.log('Init: Child');
};
var ch = new Child('it`s foo!');
ch.init('it`s init!');
Upvotes: 1
Reputation: 11929
Parent (parent.js)
function Parent() {
}
Parent.prototype.fn1 = function() {}
exports.Parent = Parent;
Child
var Parent = require('parent').Parent,
util = require('util');
function Child() {
Parent.constructor.apply(this);
}
util.inherits(Child, Parent);
Child.prototype.fn2 = function() {}
Upvotes: 0
Reputation: 30103
First of all, do not export create method, export constructor (Child, Parent). Then you will be able to call parent's constructor on child:
var c = new Child;
Parent.apply(c);
About inheritance. In node you can use util.inherits
method, which will setup inheritance and setup link to superclass. If you don't need link to superclass or just want to inherit manually, use proto:
Child.prototype.__proto__ = Parent.prototype;
Upvotes: 0