Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从子类函数调用超级函数_Javascript_Oop_Inheritance - Fatal编程技术网

Javascript 从子类函数调用超级函数

Javascript 从子类函数调用超级函数,javascript,oop,inheritance,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.protot

我希望在子类函数中调用超类函数,该子类函数重写了超类函数。例如:

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

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

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

};

将检查此操作是否有效。您可以在浏览器控制台中复制/粘贴以快速检查。