从子类函数调用超级函数

Jac*_*yan 5 javascript oop inheritance

我希望在子类函数中调用超类函数来覆盖超类函数。例如:

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) 
};
Run Code Online (Sandbox Code Playgroud)

当子类已经覆盖超类函数时,如何从子类调用超类打印函数?

cab*_*rog 3

您可以使用superclass.prototype.method.call(argThis, parameters)。在你的情况下没有参数将是a.prototype.print.call(this);

所以,你的代码将是

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

};
Run Code Online (Sandbox Code Playgroud)