นิยาม
Constructor Method ใน JavaScript ใช้สำหรับสร้างและเริ่มต้น (initialize) อ็อบเจกต์ที่สร้างจากคลาส ถ้าไม่กำหนด constructor จะใช้ Default Constructor แทน
ข้อจำกัดสำคัญ
ในหนึ่งคลาสสามารถมี Constructor Method ได้เพียงหนึ่งเดียวเท่านั้น การประกาศมากกว่าหนึ่งจะทำให้เกิด Error
ตัวอย่างการใช้งาน
<html>
<body>
<script>
class Department {
constructor() {
this.name = "Department";
}
}
class Employee extends Department {
constructor() {
super(); // เรียก constructor ของคลาสแม่
}
}
class Company {}
// ตั้งค่า Prototype Chain
Object.setPrototypeOf(Employee.prototype, Company.prototype);
// ตรวจสอบ Prototype
document.write("<br>" + (Object.getPrototypeOf(Employee.prototype) === Department.prototype));
// สร้าง Instance
let myInstance = new Employee();
document.write("<br>" + myInstance.name);
</script>
</body>
</html>
คำอธิบายโค้ด
Departmentมี constructor ตั้งค่าthis.nameEmployeeextendsDepartmentและเรียกsuper()เพื่อให้ constructor แม่ทำงานObject.setPrototypeOfเปลี่ยน prototype chain (สำหรับการสาธิต)new Employee()สร้างอ็อบเจกต์ใหม่ เรียก constructor ทั้งลูกและแม่
Constructor กับ Parameter
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person("John", 30);
Best Practices
- ใช้ constructor สำหรับ initialization เท่านั้น (หลีกเลี่ยง Side Effects)
- เรียก
super()ก่อนใช้thisในคลาสลูก - ใช้ Default Parameters สำหรับค่าที่อาจไม่ได้ส่งมา
- Validate ข้อมูลนำเข้าใน constructor