当子类在 JavaScript 中具有与父类同名的方法时,我们如何调用父类的方法?
当父类和子类具有相同的方法名称和签名时,为了调用父类方法。
你可以使用以下语法 −
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP