Proper way to call superclass functions from subclass
You can write it like this :
SuperClass.prototype.printInfo = function(){
console.log("printing from superclass printInfo");
console.log(this.info);
};
SubClass.prototype.printInfo = function(){
console.log("calling superclass");
SuperClass.prototype.printInfo.call(this);
console.log("called superclass");
};
class Thing {
constructor(age) { this.age = age; }
die(how) { console.log(`Died of ${how}`); }
}
class Me extends Thing {
constructor() { super(59); console.log(`I am ${this.age}`); }
// Refer to a method from the superclass that is overridden in the subclass
die(how) { super.die('liver failure'); console.log(`while ${how}`) }
}
(new Me()).die('hang gliding');
You are messing with the SubClass
's prototype with the SuperClass
's object, in this line
SubClass.prototype = new SuperClass();
the child's prototype should depend on the Parent's prototype. So, you can inherit like this
SubClass.prototype = Object.create(SuperClass.prototype);
Also, it is quite normal to change the constructor to the actual function, like this
SubClass.prototype.constructor = SubClass;
To keep your implementation generic, you can use Object.getPrototypeOf
, to get the parent prototype in the inheritance chain and then invoke printInfo
, like this
SubClass.prototype.printInfo = function() {
Object.getPrototypeOf(SubClass.prototype).printInfo(this);
};
Since, info
is defined in the SubClass
yet, it will print undefined
. You might also want to call the parent't constructor, like this
var SubClass = function() {
SuperClass.call(this);
};
Note: You are creating global variables, by omitting var
keyword before SuperClass
and SubClass
.
After reading all the answers, I am using the following inheritance mechanism:
var SuperClass = function()
{
this.info = "I am superclass";
console.log("SuperClass:");
};
SuperClass.prototype.printInfo = function()
{
console.log("printing from superclass printInfo");
console.log("printinfo");
console.log(this.info);
};
var SubClass = function(){
SuperClass.call(this);
};
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;
SubClass.prototype.printInfo = function()
{
console.log("calling superclass");
Object.getPrototypeOf(SubClass.prototype).printInfo.call(this);
console.log("called superclass");
};
var sc = new SubClass();
sc.printInfo();