extends
'extends' tạo kế thừa class (class inheritance). Class con kế thừa tất cả method từ class cha.
Ví dụ
Dùng 'extends' kế thừa từ class 'Company' sang class 'Model'. super() tham chiếu đến class cha. Gọi super() trong constructor là gọi constructor cha và truy cập property/method cha.
<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>
Kết quả
Tutorialspoint has a product that is Tutorix
Các điểm quan trọng:
super()phải gọi trước khi dùngthistrong constructor con- Kế thừa method: con có thể override method cha
super.method()gọi method cha từ method con- JavaScript chỉ hỗ trợ đơn kế thừa (single inheritance)