--- title: constructor slug: Web/JavaScript/Reference/Classes/constructor translation_of: Web/JavaScript/Reference/Classes/constructor ---
{{jsSidebar("Classes")}}

Phương thức constructor là một phương thức đặc biệt dùng để khởi tạo 1 object và được tạo ở trong class.

{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}

Cú pháp

constructor([arguments]) { ... }

Mô tả

Chỉ có duy nhất 1 phương thức đặc biệt tên là "constructor" ở trong class. Có nhiều hơn 1 phương thức constructor ở trong class thì sẽ gây ra lỗi{{jsxref("SyntaxError")}}.

Một constructor có thể sử dụng từ khóa {{jsxref("Operators/super", "super")}} để gọi đến constructor của class cha.

Nếu bạn không chỉ định 1 phương thức constructor thì constructor mặc định sẽ được sử dụng

Ví dụ

Sử dụng phương thức constructor 

Đoạn code này được lấy từ classes sample (live demo).

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}

Ví dụ khác

Hãy xem đoạn code sau

class Polygon {
    constructor() {
        this.name = "Polygon";
    }
}

class Square extends Polygon {
    constructor() {
        super();
    }
}

class Rectangle {}

Object.setPrototypeOf(Square.prototype, Rectangle.prototype);

console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true

let newInstance = new Square();
console.log(newInstance.name); //Polygon

Ở đây prototype của class Square đã bị thay đổi nhưng constructor kế thừa từ class Polygon vẫn được gọi khi tạo ra 1 thực thể mới.

Default constructors

Như đã nói ởi trước, nếu bạn không chỉ đỉnh 1 phương thức constructor thì default constructor sẽ được sử dụng. Với những class cơ bản thì default contructor sẽ là:

constructor() {}

Với những class dẫn xuất, default constructor sẽ là:

constructor(...args) {
  super(...args);
}

Thông số kĩ thuật

Specification Status Comment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}} {{Spec2('ES2015')}} Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}} {{Spec2('ESDraft')}}  

Browser compatibility

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

Bài viết liên quan