티스토리 뷰

00. 생성자 함수의 역할

  - 구조가 동일한 인스턴스를 생성하기 위한 템플릿으로 생성하는 것

  - 생성된 인스턴스를 초기화하는 것


function Square(side) {
  // 인스턴스 초기화
  this.side = side;
  this.getArea = function () {
    return this.side * this.side;
  };
}

// 인스턴스 생성
const square = new Square(3); // 객체 생성

this에 프로퍼티를 추가하고 필요에 따라 인스턴스를 초기화한다.

이때, 인스턴스를 생성하고 반환하는 코드는 보이지 않는다.

 

자바스크립트 엔진은 암묵적으로 인스턴스를 생성하고 반환하기 때문이다.

이러한 암묵적인 처리는 다음과 같다.

 

01. 인스턴스 생성과 this 바인딩

암묵적으로 빈 객체가 생성된다.

이 빈 객체를 this에 바인딩한다. 런타임 이전에 실행된다.

 

* 바인딩 : 식별자와 값을 연결하는 과정 ex. 식별자와 확보된 메모리 공간의 주소를 바인딩하다.

function Square(side) {
  // 암묵적으로 인스턴스 생성 후 this 바인딩
   console.log(this); // Square {}
}

 

02. 인스턴스 초기화

생성된 함수에 기술되어있는 코드를 실행하며 this 바인딩된 인스턴스를 초기화한다.

즉, 개발자는 this 인스턴스에 프로퍼티나 메서드를 추가한다.

function Square(side) {
  // 암묵적으로 인스턴스 생성 후 this 바인딩
   console.log(this); // Square {}
   
  // this에 바인딩된 인스턴스 초기화
   this.side = side;
   this.getArea = function () {
    return this.side * this.side;
  };
}

 

03. 인스턴스 반환

생성자 함수 내부 처리가 끝나면 인스턴스가 바인딩된 this를 암묵적으로 반환한다.

function Square(side) {
  // 1. 암묵적으로 인스턴스 생성 후 this 바인딩
   console.log(this); // Square {}
   
  // 2. this에 바인딩된 인스턴스 초기화
   this.side = side;
   this.getArea = function () {
    return this.side * this.side;
  };
  
  // 3. 바인딩된 this가 암묵적으로 반환된다.
}

const square = new Square(3);
console.log(square);

 

 

만약 다른 객체를 명시적으로 반환하면 return문에 명시된 객체가 반환된다.

function Square(side) {
   this.side = side;
   this.getArea = function () {
    return this.side * this.side;
  };
  // 명시적으로 객체를 반환한다.
  return {};
}

const square = new Square(3);
console.log(square); // {}

 

하지만, 명시적인 원시 값을 반환할 경우 이 반환은 무시되고 암묵적으로 this가 반환된다.

function Square(side) {
   this.side = side;
   this.getArea = function () {
    return this.side * this.side;
  };
  // 명시적으로 객체를 반환한다.
  return 100;
}

const square = new Square(3);
console.log(square); // Square { side: 3, getArea: f }

 

이러한 동작은 생성자 함수의 기본 원리를 훼손한다.

따라서 생성자 함수 내부에서 return문은 반드시 생략해야한다.

댓글