Từ khóa extends
được sử dụng trong khai báo class hoặc trong class expressions để tạo ra 1 class con là con của class khác
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Cú pháp
class ChildClass extends ParentClass { ... }
Mô tả
Từ khó extends
có thể được sử dụng để tạo ra class con từ những class mà chúng ta tạo ra hoặc những class sẵn có
Thuộc tính .prototype
của lớp được kế thừa phải trả về giá trị là Object
hoặc null
.
Ví dụ
Sử dụng extends
Ở ví dụ đầu tiên tạo ra 1 class Square
từ class Polygon
. Ví dụ này được lấy từ đây (source).
class Square extends Polygon {
constructor(length) {
// Ở đây, gọi 1 constructor từ class cha với tham số truyền vào là length
// cung cấp chiều rộng vào chiều cao của class Polygon
super(length, length);
// Chú ý: trong những class con, super() phải được gọi trước khi
// bạn có thể sử dụng từ khóa 'this'. Nếu không sẽ gây ra lỗi tham chiếu
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
}
Sử dụng extends
với những object có sẵn
Trong ví dụ này chúng ta thừa kế từ object có sẵn là Date
. Ví dụ này được lấy từ đây(source).
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}
Thừa kế từ null
Thừa kế từ null
cũng giống như class thông thường, ngoại trừ rằng các prototype của object sẽ không được thừa kế từ Object.prototype
.
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
new nullExtends(); //ReferenceError: this is not defined
Thông số kĩ thuật
Thông số | Trạng thái | Bình luận |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'extends' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'extends' in that specification. |
Living Standard |
Trình duyệt tương thích
BCD tables only load in the browser