ได้ คลาสพาเรนต์และคลาสย่อยสามารถมีเมธอดที่มีชื่อเดียวกันได้
ตัวอย่าง
class Parent {
constructor(parentValue) {
this.parentValue = parentValue;
}
//Parent class method name which is same as Child Class method name.
showValues() {
console.log("The parent method is called.....");
console.log("the value is="+this.parentValue);
}
}
class Child extends Parent {
constructor(parentValue,childValue){
super(parentValue);
this.childValue = childValue;
}
//Child class method name which is same as Parent Class method name.
showValues() {
console.log("The child method is called.....");
console.log("The value is="+`${this.childValue}`);
}
}
var parentObject = new Parent(100);
parentObject.showValues();
var childObject = new Child(400,500);
childObject.showValues(); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo195.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
PS C:\Users\Amit\javascript-code> node demo195.js The parent method is called..... the value is=100 The child method is called..... The value is=500