본문 바로가기
Front-End Study/모던 자바 스크립트_DeepDive

CH_17. 생성자 함수에 의한 객체 생성

by 코딩기 2023. 11. 18.
728x90

Object 생성자 함수

new 연산자와 함께 호출하여 빈 객체 생성 후 반환

const person = new Object();

person.name = 'lee';
person.sayhello = () => {
    console.log("Hi, My name is" + this.name);
}

console.log(person); // {name : 'lee'}
person.sayhello(); // Hi, My name is lee

생성자 함수

  • 객체 리터럴 방식의 문제점
    동일한 프로퍼티를 가진 객체를 여러개 생성해야하는 경우 하나하나 작성이 번거로움

      const circle1 = {
          radius = 5,
          getDiameter() {
              return 2 * this.radius;
          }
      }
    
      const circle2 = {
          radius = 10,
          getDiameter() {
              return 2 * this.radius;
          }
      }
      // 여러개 만드는 경우
  • 생성자 함수 방식의 장점
    객체를 생성하기 위한 클래스처럼 생성자 함수를 사용해 간편하게 여러개로 작성

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

    2. 인스턴스 초기화

    3. 인스턴스 반환

      function Circle(radius) {
       // 암묵적인 인스턴스 생성 후 this 바인딩, 바인딩된 인스턴스 초기화
       this.radius = radius;
       this.getDiameter = function () {
           return 2 * this.radius; 
       }
      }
      
      // 인스턴스 생성, 암묵적으로 this 반환
      const circle1 = new Circle(5);
      const circle2 = new Circle(10);
      console.log(circle1.getDiameter());
      // 여러개 만드는 경우(위와 동일)

    -> 다른 객체를 명시적으로 반환 시, this 반환X, return문에 명시한 객체 반환
    -> 원시 값 반환 시 무시하고 암묵적으로 this 반환


  • 내부 메서드 [[Call]] 과 [[Construct]]

    함수는 객체이므로 일반 객체와 동일하게 동작(객체가 가진 내부 슬롯, 메서드 O)
    -> 일반 객체와 다르게 호출이 가능, 추가적인 내부슬롯과 메서드를 가짐

      function foo() {}
    
      foo(); // 일반적인 함수로서 호출 : [[call]]이 호출
    
      new foo(); // 생성자 함수로서 호출 : [[Construct]] 호출

    Callable : 호출할 수 있는 객체(함수)
    Constructor : 생성자 함수로서 호출할 수 있는 함수
    non - Constructor : 생성자 함수로서 호출할 수 없는 함수

==-> 함수는 무조건 Callable 하지만 Constructor일 수도 non일 수도 있다.==

  • Constructor와 non-Constructor 구분하기
    Constructor : 함수 선언문, 표현식, 클래스(함수)
    non-Constructor : 메서드, 화살표 함수

      function foo() {}
      const bar = function() {}
      const baz = { x: function() {}}
      // 생성자 함수로서 동작
    
      const arrow = () => {}
      const obj = {x() {}}
      // 생성자 함수로서 동작X

==쓰임과 다르게 생성자로 적용하는 경우 주의!==

  • new.target
    생성자 함수가 new 없이 호출되는 것을 방지(메타 프로퍼티)

      function Circle(radius){
          if(!new.target){
              return new Circle(radius))
          }
          this.radius = radius;
          ...
      }
    
      const circle = Circle(5); // new를 붙이지 않았지만 new.target 조건문으로 생성