【问题标题】:Calling a super function from a subclass function [duplicate]从子类函数调用超级函数[重复]
【发布时间】:2015-12-14 23:16:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript oop inheritance


    【解决方案1】:

    您可以使用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);
    
    };
    

    【讨论】:

    • 将检查这是否有效。
    • 您可以复制/粘贴到浏览器的控制台中快速查看。
    猜你喜欢
    • 2013-10-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多