当子类在 JavaScript 中拥有同名方法时,我们如何调用父类的方法?
javascriptweb developmentobject oriented programming更新于 2025/11/18 19:56:17
当父类和子类拥有相同的方法名称和签名时,如何调用父类的方法。
您可以使用以下语法 −
console.log(yourParentClassName.prototype.yourMethodName.call(yourChildObjectName));
示例
class Super {
constructor(value) {
this.value = value;
}
display() {
return `The Parent class value is= ${this.value}`;
}
}
class Child extends Super {
constructor(value1, value2) {
super(value1);
this.value2 = value2;
}
display() {
return `${super.display()}, The Child Class value2
is=${this.value2}`;
}
}
var childObject = new Child(10, 20);
console.log("Calling the parent method display()=")
console.log(Super.prototype.display.call(childObject));
console.log("Calling the child method display()=");
console.log(childObject.display());
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里,文件名是 demo192.js。
输出
这将产生以下输出 −
PS C:\Users\Amit\javascript-code> node demo192.js Calling the parent method display()= The Parent class value is= 10 Calling the child method display()= The Parent class value is= 10, The Child Class value2 is=20
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

