생성자 함수(constructor) : new 연산자 와 함께 호출하여 객체(인스턴스)를 생성하는 함수

객체 리터럴({ })에 의한 객체 생성 방식의 문제점

const person1 = {
  name: "WI",
  getPersonName() {
    return `Hi, My Name is ${this.name}`;
  },
};

console.log(person1.getPersonName()); // Hi, My Name is WI

const person2 = {
  name: "YOUNGMIN",
  getPersonName() {
    return `Hi, My Name is ${this.name}`;
  },
};

console.log(person2.getPersonName()); // Hi, My Name is YOUNGMIN

생성자 함수에 의한 객체 생성 방식의 장점

// 생성자 함수 Person 선언
function Person(name) {
  this.name = name;
  this.getPersonName = function () {
    return `Hi, My Name is ${this.name}`;
  };
}

// new 연산자와 함께 Person 객체(인스턴스) 생성
const person1 = new Person("WI");
const person2 = new Person("YOUNGMIN");

// 각 Person 객체의 메서드 호출
console.log(person1.getPersonName()); // Hi, My Name is WI
console.log(person2.getPersonName()); // Hi, My Name is YOUNGMIN

자바스크립트에서 생성자 함수