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);
};
将检查此操作是否有效。您可以在浏览器控制台中复制/粘贴以快速检查。