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

한칙촉·2024년 3월 7일

Object 생성자 함수

// 빈 객체의 생성
const person = new Object();

// 프로퍼티 추가
person.name = 'Lee';
person.sayHello = function () {
  console.log('Hi! My name is ' + this.name);
};

console.log(person); // {name: "Lee", sayHello: f}
person.sayHello(); // Hi! My name is Lee
  • 생성자 함수 = new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수
  • 인스턴스 = 생성자 함수에 의해 생성된 객체
  • Object 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인 생성자 함수 제공

생성자 함수

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

const circle1 = {
  radius: 5,
  getDiameter() {
    return 2 * this.radius;
  }
};

console.log(circle1.getDiameter()); // 10

const circle2 = {
  radius: 10,
  getDiameter() {
    return 2 * this.radius;
  }
};

console.log(circle2.getDiameter()); // 20

객체 리터럴에 의한 객체 생성 방식은 단 하나의 객체만 생성


생성자 함수에 의한 객체 생성 방식의 장점

// 생성자 함수
function Circle(radius) {
  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(circle12.getDiameter()); // 20
  • 프로퍼티 구조가 동일한 객체 여러 개를 간편하게 생성 가능
  • this = 객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수

// new 연산자와 함께 호출하지 않으면 생성자 함수로 동작하지 않음
// 즉, 일반 함수로서 호출됨
const circle3 = Circle(15);

// 일반 함수로서 호출된 Circle은 반환문이 없으므로 암묵적으로 undefined를 반환
console.log(circle3); // undefined

// 일반 함수로서 호출된 Circle 내의 this는 전역 객체를 가리킴
console.log(radius); // 15
  • new 연산자와 함께 호출하면 해당 함수는 생성자 함수로 동작
  • new 연산자와 함께 호출하지 않으면 일반 함수로 동작

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

  1. 인스턴스 생성과 this 바인딩
  2. 인스턴스 초기화
  3. 인스턴스 반환
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 문에 명시한 객체가 반환됨
  • 명시적으로 원시 값을 반환하면 원시 값 반환은 무시되고 암묵적으로 this가 반환됨

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

// 함수는 객체임
function foo() {}

// 함수는 객체이므로 메서드를 소유할 수 있음
foo.prop = 10;

// 함수는 객체이므로 메서드를 소유할 수 있음
foo.method = function() {
  console.log(this.prop);
};

foo.method(); // 10

// 일반적인 함수로서 호출 : [[Call]]가 호출됨
foo();

// 생성자 함수로서 호출 : [[Construct]]가 호출됨
new foo();
  • 일반 객체는 호출할 수 없지만 함수는 호출할 수 있음
  • 모든 함수 객체는 내부 메서드에 [[Call]]을 갖고 있으므로 호출할 수 있음
  • 하지만 모든 함수 객체가 [[Construct]]를 갖는 것은 아니므로 함수 객체는 construct일 수도 있고 non-constructor일 수도 있음

constructor와 non-constructor의 구분

  • constructor = 함수 선언문, 함수 표현식, 클래스(클래스도 함수임)
  • non-constructor = 메서드(ES6 메서드 축약 표현), 화살표 함수

new 연산자

  • new 연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작
  • 단, new 연산자와 함께 호출하는 함수는 non-constructor가 아닌 constructor이어야 함

// 생성자 함수
function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

// new 연산자 없이 생성자 함수 호출하면 일반 함수로서 호출됨
const circle = Circle(5);
console.log(circle); // undefined

//일반 함수의 내부의 this는 전역 객체 window를 가리킴
console.log(radius); // 5
console.log(getDiamater()); // 10

circle.getDiameter(); 
// TypeError: Cannot read property 'getDiameter' of undefined

new.target

  • new 연산자와 함께 생성자 함수로서 호출되면 함수 내부의 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(getDiamater());
profile
빙글빙글돌아가는..

0개의 댓글