*참고 자료 - 모던 자바스크립트 Deep Dive
Object 생성자 함수
new 연산자와 함께 object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다.
빈 객체를 생성한 이후 프로퍼티 또는 메서드를 추가하여 객체를 완성할 수 있다.
const person = new Object()
person.name = 'bear'
person.sayYeah = function () {
console.log('I say ye, you say ah. alrigt? ' + this.name)
}
console.log(person)
person.sayYeah()
위 코드는 const person = new Object라는 빈 객체를 생성하고
person.name, person.say Yeah라는 프로퍼티를 추가했다.
위 코드를 호출해보면 person은
{
"name": "bear",
"sayYeah": "function () {console.log('I say ye, you say ah. alrigt? ' + this.name)}"
}
person.sayYeah()
"I say ye, you say ah. alrigt? bear"
이렇게 출력된다.
하지만 Object 생성자 함수를 사용해 빈 객체를 생성하지 않는 방법도 있다.
const person = new Object({ name: 'bear'})
person.sayHello = function () {
console.log(this.name + ', hello~')
}
person.sayHello()
bear, hello~
Object의 인수로 객체를 전달해서 새로운 객체를 생성하고,
이후에 객체의 생성값을 추가하거나 변경 할 수도 있다.
const person = new Object({ name: 'bear'})
console.log(person) // { name: 'bear' }
person.age = 5
person.sayHello = function () {
console.log(this.name + ', hello~')
}
person.sayHello() // bear, hello~
console.log(person)
/* {
"name": "bear",
"age": 5,
"sayHello": "function () {console.log(this.name + ', hello~')}"
} */
Object 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date 등의 빌트인 생성자 함수를 제공한다.
const strObj = new String('bear')
console.log(typeof srtObj) // object
console.log(strObj) // String {"bear"}
const numObj = new Number(111)
console.log(typeof numObj) // object
console.log(numObj) // Number {111}
댓글