extends
คีย์เวิร์ด 'extends' ใช้สร้าง Class Inheritance Class ที่สร้างด้วย Inheritance จะสืบทอดทุกเมธอดจาก Class อื่น มาดูรายละเอียดกัน
ตัวอย่าง
ในตัวอย่างนี้ ใช้ 'extends' เพื่อ สืบทอด Properties จาก Class 'Company' ไปยัง Class 'Model' เมธอด super() อ้างถึง Parent Class การเรียก super() ใน Constructor คือการเรียก Constructor ของ Parent และเข้าถึง Properties/Methods ของ Parent ได้
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } method() { return this.name + " has a product that is "; } } class Model extends Company { constructor(branch, pname) { super(branch); this.model = pname; } result() { return this.method() + " " + this.model; } } mycar = new Model("Tutorialspoint", "Tutorix"); document.getElementById("method").innerHTML = mycar.result(); </script> </body> </html>
ผลลัพธ์
Tutorialspoint has a product that is Tutorix