𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀

Constructor function คือพิมพ์เขียวสำหรับออบเจกต์ (objects) ใช้สำหรับสร้างออบเจกต์จำนวนมากที่มีโครงสร้างเหมือนกัน

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

คุณใช้ keyword new เพื่อเรียกใช้ constructor function ซึ่งกระบวนการนี้จะทำ 4 อย่างดังนี้:

ตัวอย่างโค้ด:

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

const emp1 = new Employee("Saravanan", 50000);

กฎที่ควรปฏิบัติตาม:

บทบาทของ this:

ภายใน constructor ตัว this จะอ้างถึงออบเจกต์เฉพาะที่คุณกำลังสร้างขึ้น ตัวอย่างเช่น this.name = name จะเป็นการกำหนดค่าจาก parameter ให้กับ property ของออบเจกต์

การเพิ่ม methods:

คุณสามารถเพิ่มฟังก์ชันไว้ภายใน constructor เพื่อให้ออบเจกต์ทุกตัวสามารถเรียกใช้งานได้

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

ประสิทธิภาพในการใช้หน่วยความจำ:

หากคุณเพิ่ม methods ลงใน constructor โดยตรง ออบเจกต์แต่ละตัวจะมีสำเนาเป็นของตัวเอง ซึ่งจะทำให้สิ้นเปลืองหน่วยความจำมากขึ้น

ในทางกลับกัน ให้ใช้ prototype การเพิ่ม method ลงใน prototype จะช่วยให้ออบเจกต์ทั้งหมดใช้สำเนาเดียวกันเพียงชุดเดียว

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

สรุป:

Source: https://www.w3schools.com/js/js_object_constructors.asp Source: https://www.geeksforgeeks.org/javascript/javascript-function-constructor/ Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

Post link: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k