--- title: extends(Thừa kế) slug: Web/JavaScript/Reference/Classes/extends translation_of: Web/JavaScript/Reference/Classes/extends ---
{{jsSidebar("Classes")}}

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

{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}

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à  {{jsxref("Object")}} hoặc {{jsxref("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à {{jsxref("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ừ {{jsxref("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ừ {{jsxref("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
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}} {{Spec2('ES2015')}} Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}} {{Spec2('ESDraft')}}  

Trình duyệt tương thích

{{Compat("javascript.classes.extends")}}

Bài viết liên quan