JavaScript Constructor Functions

ใช้ constructor functions เพื่อสร้างออบเจกต์จำนวนมากที่มีโครงสร้างเหมือนกัน

Constructor function ทำหน้าที่เป็นเหมือนพิมพ์เขียว (blueprint) คุณจะใช้ keyword new เพื่อสร้างออบเจกต์จากพิมพ์เขียวนี้ และคุณควรเริ่มต้นชื่อของ constructor ด้วยตัวอักษรพิมพ์ใหญ่

หลักการทำงาน:

เมื่อคุณใช้ keyword new JavaScript จะดำเนินการ 4 อย่างดังนี้:

keyword this มีความสำคัญอย่างยิ่ง ภายในฟังก์ชัน this จะอ้างถึงออบเจกต์ใหม่ของคุณ

ตัวอย่าง:

function Employee(name, salary) {
    this.name = name;
    this.salary = salary;
}

const emp1 = new Employee("Ram", 50000);
const emp2 = new Employee("Kumar", 60000);

ออบเจกต์ทั้งสองมีโครงสร้างแบบเดียวกัน

การเพิ่มเมธอด (Adding methods):

คุณสามารถเพิ่มฟังก์ชันเข้าไปภายใน constructor ได้

function Employee(name, salary) {
    this.name = name;
    this.salary = salary;
    this.displayInfo = function() {
        console.log(this.name + " earns " + this.salary);
    };
}

การจัดการหน่วยความจำ (Memory management):

การเพิ่มเมธอดลงใน constructor โดยตรงจะทำให้เกิดการสร้างสำเนาใหม่สำหรับทุกๆ ออบเจกต์ ซึ่งจะใช้หน่วยความจำมากขึ้น

แทนที่จะทำเช่นนั้น ให้ใช้คุณสมบัติ prototype แทน

Employee.prototype.greet = function() {
    console.log("Hello " + this.name);
};

ตอนนี้ พนักงานทุกคนจะใช้เมธอด greet ร่วมกันเพียงชุดเดียว ซึ่งจะช่วยให้โค้ดของคุณมีประสิทธิภาพมากขึ้น

สรุป:

แหล่งที่มา: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k