5

I am looking to call a superclass function within a subclass function that overrode the superclass function. For Example:

var a = function(x) {
    this.val = x || 0;
};
a.prototype.print = function() {
    console.log("Class A");
};

var b = function(x, y) {
   this.y = y || 0;
   a.call(this, x);
};
b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;
b.prototype.print = function() {
    console.log("b inherits from ");
    // call to superclass print function (a.print) 
};

How would I call the superclass print function from the subclass when the subclass already overwrote the superclass function?

Jacob Bryan
  • 496
  • 4
  • 12

1 Answers1

3

You can use superclass.prototype.method.call(argThis, parameters). In your case without parameters will be a.prototype.print.call(this);

So, your code would be

var a = function(x) {
    this.val = x || 0;
};
a.prototype.print = function() {
    console.log("Class A");
};

var b = function(x, y) {
   this.y = y || 0;
   a.call(this, x);
};
b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;
b.prototype.print = function() {
    console.log("b inherits from ");
    a.prototype.print.call(this);

};
caballerog
  • 2,679
  • 1
  • 19
  • 32