當子類在 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