Định nghĩa
constructor() là method đặc biệt trong class, tự động chạy khi tạo instance bằng new. Dùng để khởi tạo property.
Quy tắc
- Mỗi class chỉ có một constructor.
- Derived class (extends) bắt buộc gọi
super()trước khi dùngthis. - Không trả về giá trị (tự động trả instance).
Ví dụ cơ bản
<script>
class Department {
constructor() {
this.name = "Department";
}
}
class Employee extends Department {
constructor() {
super(); // gọi parent constructor
}
}
let emp = new Employee();
document.write(emp.name); // "Department"
</script>
Ví dụ có tham số
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I'm ${this.name}, ${this.age}`);
}
}
const p = new Person("An", 25);
p.greet(); // "Hi, I'm An, 25"
Constructor vs Factory Function
| Constructor (class) | Factory Function |
|---|---|
Dùng new | Gọi thường (không new) |
this = instance mới | Tự tạo object, trả về |
| Prototype chain tự động | Tự quản lý prototype |
| ES6 class syntax | Function bình thường |
Lưu ý
- Không dùng
returntrong constructor (trừ return object khác – hiếm). super()có thể truyền args:super(name, age).