13. Creating objects by constructor functions

객체리터럴 외의 생성자 함수에 의한 객체 생성방식를 이해해보자

Index

Object 생성자 함수

생성자 함수

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

new 연산자



1. Object 생성자 함수

new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다.

빈 객체를 생성한 이후 프로퍼티 또는 메서드를 추가하여 객체를 완성할 수 있다.

생성자 함수(constructor)란 new연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스(instance)라 한다.

// 빈 객체의 생성
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



2. 생성자 함수

2.1 생성자 함수의 장점

🤓 Q. Object 생성자 함수를 사용해 객체를 생성하는 방식은 유용하다고 볼 수 있는가?

Problem. 객체 생성 시 매번 같은 프로퍼티 기술 해야하는 비효율성

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


Advantage. 객체를 생성하기 위한 탬플릿처럼 동일한 객체 생성

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

// 인스턴스의 생성
const circle1 = new Circle(5); // 반지름이 5인 Circle 객체를 생성
const circle2 = new Circle(10); // 반지름이 10인 Circle 객체를 생성

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



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

2.2.1 인스턴스 생성과 this 바인딩

function Circle(radius) {
  // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
  console.log(this); // Circle {}

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


2.2.2 인스턴스 초기화

this에 바인딩되어 있는 인스턴스에 프로퍼티나 메서드를 추가하고 생성자 함수가 인수로 전달받은 초기값을 인스턴스 프로퍼티에 할당하여 초기화하거나 고정값을 할당한다.

function Circle(radius) {
  // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
  console.log(this); // Circle {}

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


2.2.3 인스턴스 반환

function Circle(radius) {
  // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
  console.log(this); // Circle {}

  // 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) {
  console.log(this);

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

const circle = new Circle(1);
console.log(circle); // {}
ⅱ) 명시적으로 원시값을 반환하면 원시 값 반환은 무시되고 암묵적으로 this가 반환된다.
function Circle(radius) {
  console.log(this);

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

const circle = new Circle(1);
console.log(circle); // Circle{radius:1, getDiameter: f}

생성자 함수 내부에서 명시적으로 this가 아닌 다른 값을 반환하는 것은 생성자 함수의 기본 동작을 훼손한다.

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



3. 내부 메서드 [[Call]], [[Construct]]

일반 객체는 호출할 수 없지만 함수는 호출할 수 있다. 따라서 함수 객체는 일반 객체가 가지고 있는 내부 슬롯과 내부 메서드는 물론,

함수로서 동작하기 위해 함수 객체만을 위한
[[Environment]], [[Formal Parameters]] 등의 내부 슬롯과
[[Call]], [[Contruct]] 같은 내부 메서드 를 추가로 가지고 있다.

ⅰ) 일반 함수로서 호출 되면 => 함수 객체의 내부 메서드 [[Call]]이 호출되고

ⅱ) new연산자와 함께 생성자 함수로서 호출되면 => 내부 메서드 [[Construct]] 가 호출된다.

Photo of constructor

constructor

Jay Tak.


자바스크립트 엔진은 함수 정의를 평가하여 함수객체를 생성할 때 함수 정의 방식에 따라 함수를 constructor와 non-consctructor로 구분한다.

// 일반 함수 정의: (1) 함수선언문, (2) 함수표현식, (3) 프로퍼티에 할당된 일반함수
1;
function foo() {}
2;
const bar = (function () {})(3);
const baz = {
  x: function () {},
};

new foo();
new bar();
new baz.x();

// 화살표 함수
const arrow = () => {};
new arrow(); // TypeError: arrow is not a consctructor

// 메서드 정의: Es6의 메서드 축약 표현만 메서드로 인정한다.
const obj = {
  x() {},
};
new obj.x(); // TypeError: obj.x is not a consctructor



4. new 연산자

new 연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작한다. 다시 말해, 함수 객체의 내무 메서드 [[Call]]이 호출되는 것이 아니라 [[Construct]]가 호출된다. 단, new 연산자돠 함께 호출하는 함수는 non-constructor가 아닌 constructor이어야 한다.

// (1) 생성자 함수로서 정의되지 않은 함수
function add(x, y) {
  return x + y;
}

// 생성자 함수로서 정의하지 않은 함수를 new 연산자와 함께 호출
let inst = new add();

// 함수가 객체를 반환하지 않았으므로 반환문이 무시된다. 따라서 빈 객체가 생성되어 반환된다.
console.log(inst); {}

// (2) 객체를 반환하는 일반 함수
function createUser(name, role) {
  return {name, role};
}

// 일반 함수를 new 연산자와 함께 호출
inst = new createUser('Lee', 'admin');

// createUser는 생성자 함수로 동작하지 않는다. 단지 생성한 객체만 반환
console.log(inst); // {name: 'Lee', role: 'admin'}

생성자 함수로 작동하도록 변경하려면!
=> return 문을 제거하고, this를 사용해 속성을 정의해야 합니다:

function createUser(name, role) {
    this.name = name;
    this.role = role;
}

const inst = new createUser("Lee", "admin");
console.log(inst); // { name: 'Lee', role: 'admin' }




reference: 모던자바스크립트 Deep Dive 17장. 생성자 함수에 의한 객체 생성