1

I have the following code where there are two functions a, c and c is inheriting from a.

function a(){
    console.log("constructor-a");
}

a.prototype.fun1 = function(){
    console.log("a-fun1");
}
a.prototype.fun2 = function(){
    console.log("a-fun2");
}


function c(){
    c.super_.call(this)
    console.log("constructor-c");
}

c.prototype.fun5 = function(){
    console.log("c-fun1");
}
c.prototype.fun6 = function(){
    console.log("c-fun2");
}
util.inherits(c,a);

var X = new c();
console.log("X instanceof a", X instanceof a);
console.log("X instanceof a", X instanceof c);

Since c is inheriting from a, the functions of both c and a should be executable from an object of C, however, in this case the outputs are as follows:

X.fun1() --> a-fun1
X.fun2() --> a-fun2
X.fun5() --> TypeError: X.fun5 is not a function
X.fun6() --> TypeError: X.fun6 is not a function
1
  • util.inherits needs to be called before assignments to the prototype. Commented Feb 16, 2017 at 5:08

1 Answer 1

1

Do util.inherits(c,a) first and then create fun5 and fun6.

function c(){
    c.super_.call(this)
    console.log("constructor-c");
}

util.inherits(c,a);

c.prototype.fun5 = function(){
    console.log("c-fun1");
}
c.prototype.fun6 = function(){
    console.log("c-fun2");
}

This is because of the very implementation of util.inherits. That function will re-assign prototype of c with the parent's one instead of merging. So let util.inherits assign b's prototype to c's first and then add extra functions you want.

Sign up to request clarification or add additional context in comments.

Comments

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.