객체 리터럴을 사용할 수 있는 상황에서는 new Object() 생성자를 쓸 이유가 없다.


하지만 다른사람이 작성한 레거시 코드를 물려받을 수도 있기 때문에 이 생성자의 '기능' 하나를 알아 둘 필요가 있다.



Object()는 인자를 받을 수 있는데 이 값에 따라 맞는 생성자로 객체를 생성한다.

//빈 객체
var o = new Object();
console.log(o.constructor === Object);    // true

// 숫자 객체
var o = new Object(1);
console.log(o.constructor === Number);    // true
console.log(o.toFixed(2));    // "1.00"

// 문자열 객체
var o = new Object("I am string");
console.log(o.constructor === String);    // true
console.log(typeof o,substring);            // "function"

// 불린 객체
var o = new Object(true);
console.log(o.constructor === Boolean);    // true



따라서 어떤 상황이 발생할 지 모르므로 Object로는 객체를 생성하지 말자.


+ Recent posts