생성자 함수(constructor)

new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다.

JS는 Object 생성자 함수 외에도 String, Number, Boolean, Function 등의 빌트인 생성자 함수를 제공한다.

const numObj = new Number(123);
console.log(typeof numbObj); // object
console.log(numbObj); // Number { 123 }

생성자 함수의 생성 과정

function Circle(radius) {
  // 1. 암묵적으로 빈 객체가 생성되고 this에 바인딩된다.

  // 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };

  // 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
}

// 인스턴스 생성. Circle 생성자 함수는 암묵적으로 this를 반환한다.
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: f}

만약 this가 아닌 다른 객체를 명시적으로 반환하면 this가 반환되지 못하고 return 문에 명시한 객체가 반환된다. 이는 생성자 함수의 기본 동작을 훼손하기에 사용하지 않는 것이 좋다.

function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };

  return {}; // 생성자 함수가 반환하는 객체
}

// 인스턴스 생성. Circle 생성자 함수는 암묵적으로 this를 반환한다.
const circle = new Circle(1);
console.log(circle); // {}

하지만 반환 값으로 원시값을 명시해두면, 값 반환은 무시되고 this를 반환한다.

함수와 생성자

함수도 객체이기 때문에 생성자 함수로 호출할 수 있다. 하지만 함수는 객체이지만 일반 객체와는 다르다. 일반 객체는 호출할 수 없지만 함수는 호출할 수 있다.

따라서 함수 객체는 일반 객체가 가지고 있는 내부 슬롯과 내부 메서드는 물론, 함수로서 동작하기 위해 함수 객체만을 위한 [[Environment]], [[FormalParameters]] 등의 내부 슬롯과 [[Call]], [[Construct]] 같은 내부 메서드를 추가로 가지고 있다.

function foo() {}

// callable : 일반적인 함수로서 호출: [[Call]]이 호출된다.
foo();

// constructor : 생성자 함수로서 호출: [[Construct]]가 호출된다.
new foo();

함수가 일반 함수로서 호출되면 함수 객체의 내부 메서드 [[Call]]이 호출되고 new 연산자와 함께 생성자 함수로서 호출되면 내부 메서드 [[Construct]]가 호출된다.

결론적으로 함수 객체는 호출할 수 있는 callable이면서 constructor이거나, callable이면서 non-constructor(생성자가 아닌)다.

image.png

const arrow = () => {};
new arrow(); //TypeError

this와 생성자 함수, new.target

function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };

}

const circle = Circle(1); // 일반 함수로 호출
console.log(circle); //