constructor() đặc biệt: khởi tạo property, tự động gọi khi tạo instance. Nếu không có, JS thêm constructor rỗng ẩn. Có thể tự tạo method riêng với cú pháp tương tự.
Ví dụ
Thay vì constructor, property được khởi tạo trong method tự đặt tên "anotherMet()".
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } anotherMet(x) { return x + " is the head of " + this.name; } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = myComp.anotherMet("Elon musk"); </script> </body> </html>
Kết quả
Elon musk is the head of Tesla
Lưu ý: Ví dụ này vẫn dùng constructor để set this.name. Method anotherMet chỉ là method bình thường. Có thể tạo nhiều method tùy ý trong class.