// 빈 객체 생성
const person = new Object();
// 프로퍼티 추가
person.name = "Jeong";
person.intro = function () {
console.log(`Hi! My name is ${this.name}`)
};
console.log(person.name); // Jeong
person.intro(); // Hi! My name is Jeong
생성자 함수란 new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스라 한다.
객체 리터럴에 의한 생성 방식은 직관적이고 간편하나 단 하나의 객체만 생성한다.
따라서 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우는 생성자 함수에 의한 객체 생성 방식이 유리하다.
// 객체 리터럴 방식
const circle = {
radius: 5,
getDiameter() {
return 2 * this.radius;
}
};
// 생성자 함수 방식
function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
const circle = new Circle(5);
생성자 함수의 역할은 인스턴스를 생성하는것과 생성된 인스턴스를 초기화 하는것이다.
// 생성자 함수 방식
function Circle(radius) {
// 인스턴스 초기화
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// 인스턴스 생성
const circle = new Circle(5);
// 화살표 함수
const arrow = () => {};
new arrow(); // Error
// 메서드 정의
const obj = {
x() {}
};
new obj.x() // Error
new 연산자와 함께 생성자 함수로서 호출되면 함수 내부의 new.target은 함수 자신을 가리킨다. new 연산자 없이 일반 함수로서 호출된 함수 내부의 new.target은 undefined다.
쉽게 말해서, new.target 속성(property)은 함수 또는 생성자가 new 연산자를 사용하여 호출됐는지를 감지할 수 있다.