✅ 객체를 생성하는 여러가지 방법 중 이번엔 생성자 함수를 사용해 객체를 생성하는 방식을 알아보자
// 빈 객체의 생성
const person = new Object();
// 프로퍼티 추가
person.name = 'Lee';
person.sayHello = function () {
console.log('Hi! My name is ' + this.name);
};
console.log(person); // {name: "Lee", sayHello: ƒ}
person.sayHello(); // Hi! My name is Lee
//생성자 함수
function Circle(radius) {
//this는 생성자함수가 생성할 인스턴스를 가리킨다.
this.radius = radius;
this.getDiameter = function () {
return 2*this.radius;
};
}
//인스턴스 생성
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter()); //10
console.log(circle2.getDiameter()); //20
생성자 함수의 역할
- 인스턴스를 생성
- 생성된 인스턴스를 초기화(인스턴스 프로퍼티 추가 및 초기값 할당)하는 것
//생성자 함수
function Circle(radius) {
//1. 암묵적으로 빈 객체가 생성되고 this에 바인딩된다.
//2. this에 바인딩되어 있는 인스턴스로 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2*this.radius;
};
//3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
}
//인스턴스 생성. Circle 생성자 함수는 암묵적으로 this를 반환한다.
const circle1 = new Circle(5);
[[Environment]]
, [[FormalParameters]]
등의 내부 슬롯과, [[Call]]
[[Construct]]
같은 내부 메서드를 추가로 가지고 있다.함수 정의 방식에 따라 구분한다.
- constructor : 함수 선언문, 함수 표현식, 클래스(클래스도 함수다)
- non-constructor: 메서드(ES6 메서드 축약 표현만 인정한다), 화살표 함수
// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo() {}
const bar = function () {};
// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수다. 이는 메서드로 인정하지 않는다.
const baz = {
x: function () {}
};
// 일반 함수로 정의된 함수만이 constructor이다.
new foo(); // -> foo {}
new bar(); // -> bar {}
new baz.x(); // -> x {}
// 화살표 함수 정의
const arrow = () => {};
new arrow(); // TypeError: arrow is not a constructor
// 메서드 정의: ES6의 메서드 축약 표현만을 메서드로 인정한다.
const obj = {
x() {}
};
obj.x(); // TypeError: obj.x is not a constructor
일반함수와 생성자 함수에 특별한 형식적 차이는 없다.
non-constructor
가 아닌 constructor
이어야 한다.new.target
은 함수 자신을 가리킨다. new 연산자 없이 일반 함수로서 호출된 함수 내부의 new.target
은 undefined
다.// 생성자 함수
function Circle(radius) {
// 이 함수가 new 연산자와 함께 호출되지 않았다면 new.target은 undefined다.
if(!new.target) {
// new 연산자와 함께 생성자 함수를 재귀 호출하여 생성된 인스턴스를 반환한다.
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수를 호출하여도 new.target을 통해 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter());