Để gọi phương thức cha khi cả cha và con có cùng tên và chữ ký của phương thức.
Bạn có thể sử dụng cú pháp dưới đây -
console.log(yourParentClassName.prototype.yourMethodName.call(yourChildObjectName));
Ví dụ
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()); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo192.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
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