JavaScript 생성자 함수

생성자 함수는 객체를 위한 설계도입니다. 동일한 구조를 가진 여러 객체를 생성할 때 사용합니다.

작동 방식:

new 키워드를 사용하여 생성자 함수를 호출합니다. 이 과정은 다음 네 가지 작업을 수행합니다:

예제 코드:

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

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

준수해야 할 규칙:

this의 역할:

생성자 내부에서 this는 현재 생성 중인 특정 객체를 참조합니다. 예를 들어, this.name = name은 매개변수 값을 객체 속성에 할당합니다.

메서드 추가하기:

생성자 내부에 함수를 추가하여 모든 객체가 해당 함수를 사용할 수 있게 할 수 있습니다.

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);
};

요약:

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

포스트 링크: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k