new 연산자와 함꼐 Object 생성자 함수를 호출하면 빈 객체를 생성해 반환한다..
//빈객체 생성
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
생성자 함수(constructor)란 new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스라 한다
c.f 생성자 함수 = 붕어빵틀
인스턴스 = 붕어빵 틀로 찍어낸 붕어빵
- 자바스크립트는 Object 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인 함수를 제공한다.
const strObj = new String('Lee'); //String
const numObj = new Number(123); //Number
const boolObj = new Boolean(true); //Boolean
const func = new Function('x', 'return x * x'); //Function
const arr = new Array(1, 2, 3); //Array 객체(배열)
const regExp = new RegExp(/ab+c/i); //정규표현식
const date = new Date();
console.log(typeof strObj, numObj,); //object
console.log(strObj, numObj);
console.log(typeof func); //function
console.log(func);
객체 리터럴에 의한 생성 방식은 직관적이고 간편하하다
하지만, 한 번에 단 하나의 객체만 생성하기에 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우 매번 써줘야 돼서 비효율적이다.