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

동일한 구조를 가진 여러 객체를 생성하려면 생성자 함수를 사용하세요.

생성자 함수는 설계도 역할을 합니다. new 키워드를 사용하여 이 설계도로부터 객체를 만듭니다. 생성자 이름은 대문자로 시작해야 합니다.

작동 방식:

new 키워드를 사용하면 JavaScript는 다음 네 가지 작업을 수행합니다:

this 키워드는 필수적입니다. 함수 내부에서 this는 생성된 새 객체를 참조합니다.

예시:

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

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

두 객체 모두 동일한 구조를 공유합니다.

메서드 추가하기:

생성자 내부에 함수를 추가할 수 있습니다.

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

메모리 관리:

생성자 내부에 직접 메서드를 추가하면 객체마다 새로운 복사본이 생성됩니다. 이는 더 많은 메모리를 사용합니다.

대신 prototype 속성을 사용하세요.

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

이제 모든 직원은 greet 메서드의 단일 복사본을 공유합니다. 이를 통해 코드가 더 효율적으로 변합니다.

요약:

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