1

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());  
};

3 Answers 3

1

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!');
Sign up to request clarification or add additional context in comments.

Comments

0

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;

2 Comments

Problem is, Parent class is from a framework. I dont like to change the source code of a framework. Is there any other way??
Of course no. There's way around: create instance of parent, create instance of child, and then: child.constructor.prototype.__proto__ = parent.constructor.prototype
0

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() {}

1 Comment

Problem is, Parent class is from a framework. I dont like to change the source code of a framework. Is there any other way??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.