Call a superfunction from a subclass function

I want to call a superclass function in a subclass function that overrides 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 can I call the print function of a superclass from a subclass when the subclass has already overwritten the function of the superclass?

+4
source share
1 answer

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

So your code will 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);

};
+3
source

Source: https://habr.com/ru/post/1620011/


All Articles