Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Parent และ Child Classes สามารถมี Method ชื่อเดียวกันได้ไหมใน JavaScript

คำตอบ

ได้ Parent และ child classes สามารถมี method ชื่อเดียวกันได้ (Method Overriding)

ตัวอย่างโค้ด

class Parent { 
  constructor(parentValue) { 
    this.parentValue = parentValue; 
  } 
  // Parent class method name เหมือน 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 เหมือน 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

คำอธิบาย

Child class extends Parent และ define showValues() ใหม่ → Override parent method
เรียก parentObject.showValues() ใช้ parent method
เรียก childObject.showValues() ใช้ child method (override แล้ว)
สามารถเรียก parent method ได้ด้วย super.showValues() ภายใน child method