목표: 다양한 객체 생성 방식 중에서 생성자 함수를 사용하여 객체를 생성하는 방식을 살펴보기

17.1 Object 생성자 함수

// 빈 객체 생성 (person)
const person = new Object();

// 프로퍼티(속성) 추가
person.name = 'Lee';
person.sayHello = function(){
  console.log('Hi! My name is' + this.name);
}

console.log(person); // {name: "Lee", sayHello: f}
person.sayHello(); // Hi! My name is Lee

생성자 함수

// String 생성자 함수에 의한 String 객체 생성
const strObj = new String('Lee');
console.log(typeof strObj); // object
console.log(strObj); // [String: 'Lee']

// Number 생성자 함수에 의한 Number 객체 생성
const NumObj = new Number(123); 
console.log(typeof NumObj); //object
console.log(NumObj); // [Number: 123]

// Boolean 생성자 함수에 의한 Boolean 객체 생성
const boolObj = new Boolean(true); 
console.log(typeof boolObj); // object
console.log(boolObj); // [Boolean: true]

// Function 생성자 함수에 의한 Function 객체(함수) 생성
const func = new Function('x', 'return x * x'); 
console.log(typeof func); // function
console.dir(func); // f anonymous(x)

// Array 생성자 함수에 의한 Array 객체(배열) 생성
const arr = new Array(1,2,3); 
console.log(typeof arr); // object
console.log(arr); // [ 1, 2, 3 ]

// RegExp 생성자 함수에 의한 RegExp 객체(정규 표현식) 생성
const regExp = new RegExp(/ab+c/i); 
console.log(typeof regExp); // object
console.log(regExp); // /ab+c/i

// Date 생성자 함수에 의한 Date 객체 생성
const date = new Date(); 
console.log(typeof date); // object
console.log(date); // 2025-06-03T09:23:29.965Z

17.2 생성자 함수

17.2.1 객체 리터럴에 의한 객체 생성 방식의 문제점

<aside> 💡

단점:

const circle1 = {
  radius: 5,
  getDiamerter(){
    return 2*this.radius;
  }
};

console.log(circle1.getDiamerter()); // 10

const circle2 = {
  radius: 10,
  getDiamerter(){
    return 2*this.radius;
  }
};

console.log(circle2.getDiamerter()); // 20

객체: