17장 생성자 함수에 의한 객체 생성

Eriniss·2022년 10월 18일
0
post-thumbnail

17.1 Object 생성자 함수

// 빈 객체 생성
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 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스라 한다.

17.2 생성자 함수

17.2.1 객체 리터럴에 의한 객체 생성 방식의 문제점

객체 리터럴에 의한 생성 방식은 직관적이고 간편하나 단 하나의 객체만 생성한다.

따라서 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우는 생성자 함수에 의한 객체 생성 방식이 유리하다.

// 객체 리터럴 방식
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);

17.2.3 생성자 함수의 인스턴스 생성 과정

생성자 함수의 역할은 인스턴스를 생성하는것과 생성된 인스턴스를 초기화 하는것이다.

// 생성자 함수 방식
function Circle(radius) {
  // 인스턴스 초기화
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

// 인스턴스 생성
const circle = new Circle(5);

17.2.5 constructor와 non-constructor의 구분

  • constructor : 함수 선언문, 함수 표현식, 클래스(클래스도 함수다)
  • non-constructor : 메서드(ES6 메서드 축약 표현), 화살표 함수
// 화살표 함수
const arrow = () => {};

new arrow(); // Error

// 메서드 정의
const obj = {
  x() {}
};

new obj.x() // Error

17.2.7 new.target

new 연산자와 함께 생성자 함수로서 호출되면 함수 내부의 new.target은 함수 자신을 가리킨다. new 연산자 없이 일반 함수로서 호출된 함수 내부의 new.target은 undefined다.

쉽게 말해서, new.target 속성(property)은 함수 또는 생성자가 new 연산자를 사용하여 호출됐는지를 감지할 수 있다.

0개의 댓글