[모던 자바스크립트 딥다이브] 17장 생성자 함수에 의한 객체 생성

Narcoker·2022년 10월 26일
0

✏️Object 생성자 함수

new 연산자와 함께 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 등의
빌트인 생성자 함수를 제공한다.

// String 생성자 함수에 의한 String 객체 생성
const strObj = new String("Lee");
console.log(typeof strObj); // object
console.log(strObj); // String {"Lee"}

// Number 생성자 함수에 의한 Number 객체 생성
const numObj = new Number(123);
console.log(typeof numObj); // object
console.log(numObj); // Number {123}

// Boolean 생성자 함수에 의한 Boolean 객체 생성
const boolObj = new Boolean(true);
console.log(typeof boolObj); // object
console.log(boolObj); // Boolean {true}

// Function 생성자 함수에 의한 Function 객체 생성
const func = new Function('x', 'return x*x');
console.log(typeof func); // function
console.log(func); // f anonymous(x)

// Array 생성자 함수에 의한 Array 객체 생성
const arr = new Array(1,2,3);
console.log(typeof arr); // object
console.log(arr); // [1,2,3]

// RegExp 생성자 함수에 의한 RegExp 객체 생성
const regExp = new RegExp(/ab+c/i);
console.log(typeof regExp); // object
console.log(regExp); // /ab+c/i

// Date 생성자 함수에 의한 Date 객체 생성
const date = new Date();
console.log(typeof date); // object
console.log(date); // Wed Oct 26 2022 17:21:12 GMT+0900 (한국 표준시)

반드시 Object 생성자 함수를 사용해 빈 객체를 생성해야하는 것은 아니다.
객체를 생성하는 방법은 객체 리터럴을 사용하는 것이 더 간편하다.

Object 생성자 함수를 사용해 객체를 생성하는 방식은 특별한 이유가 아니면
유용하지 않다.

✏️생성자 함수

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

객체 리터럴에 의한 객체 생성 방식은 단 하나의 객체만 생성한다.
따라서 동일한 프로퍼티를 갖는 객체를 여러개 생성하는 경우
매번 같은 프로퍼티를 기술해야해서 비효율적이다.

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는 생성자 함수가 생성할 인스턴스를 가리킨다.
  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(circle2.getDiameter()); // 20

this

this는 객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수다.
this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 따라 동적으로 결정된다.

함수 호출 방식this가 가리키는 값(this 바인딩)
일반 함수로서 호출전역 객체
메서드로서 호출메서드를 호출한 객체(마침표 앞의 객체)
생성자 함수로서 호출생성자 함수가 (미래에) 생성할 인스턴스
function foo() {
	console.log(this);
}

// 일반적인 함수로서 호출
// 전역 객체는 브라우처 환경에서는 window, Node.js환경에서는 global을 가리킨다.
foo(); // window

const obj = { foo }; // ES6 프로퍼티 축약 표현
// 메서드로서 호출
obj.foo(); // obj

// 생성자 함수로서 호출
const inst = new foo(); // inst

생성자 함수는 이름 그대로 객체(인스턴스)를 생성하는 함수다.
일반함수와 동일한 방법으로 생성자 함수를 정의하고 new 연산자와 함께 호출하면
해당 함수는 생성자 함수로 동작한다.

만약 new 연산자를 사용하지 않고 함수를 호출하면 일반 함수로 동작한다.

function Circle(radius) {
  // 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  this.radius = radius;
  this.getDiameter = function() {
     return 2 * this.radius;
  };
}

const circle3 = Circle(15);

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

// 일반함수로 호출된 Circle 내의 this는 전역 객체(window, global)를 가리킨다.
console.log(radius); // 15

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

생성자함수의 역할은 프로퍼티 구조가 동일한 인스턴스를
생성하기 위한 템플릿(클래스)으로서 동작하여 인스턴스를 생성하는 것과
생성된 인스턴스를 초기화(인스턴스 프로퍼티 추가 및 초기값 할당)하는 것이다.

생성자 함수 내부의 코드를 살펴보면 this 프로퍼티를 추가하고 필요에 따라
전달된 인수를 프로퍼티 초기값으로서 할당하여 인스턴스를 초기화한다.
하지만 인스턴스를 생성하고 반환하는 코드는 보이지 않는다.

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

const circle1 = new Circle(5);

new 연산자와 함게 생성자 함수를 호출하면 자바스크립트 엔진은
다음과 같은 과정으로 인스턴스를 생성하고 반환한다.

function Circle(radius) {
  // 1. 암묵적으로 빈 객체가 생성되고 this에 바인딩 된다.

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

  // 3. 암묵적으로 this를 반환한다.
}

const circle1 = new Circle(5);

주의점

만약 return 문을 사용하여 다른 객체를 명시적으로 반환하면
this가 반환되지 않고 명시적 객체가 반환된다.

return 문을 사용하여 원시값을 반환하면
this가 반환된다.

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

  return {} 또는 100
}

const circle1 = new Circle(5); // {} 또는 Circle {radius: 1, getDiameter: f}

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

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

함수도 객체이기 때문에 일반 객체가 가지고 있는
내부 슬롯과 내부 메소드를 모두 가지고 있다.

일반 객체는 호출할 수 없지만 함수는 호출할 수 있는데
[[Envirmonment]], [[FormalParameters]] 등의 내부 슬롯과
[[Call]], [[Construct]] 같은 내부 메서드를 추가적으로 가지고 있다.

함수가 일반 함수로서 호출되면 [[Call]]이 호출되고
생성자 함수로서 호출되면 [[Construct]]가 호출된다.

내부 메서드 [[Call]] 를 갖는 함수 객체를 callable이라 하며,
내부 메서드 [[Construct]] 를 갖는 함수 객체는 constructor,
갖지 않는 함수 객체를 non-constructor 이라고 부른다.

모든 함수 객체가 [[Constuct]]를 갖는 것은 아니다.
함수 객체는 callable 이면서 constructor 이거나
callable 이면서 non-constructor다.

constructor와 non-constructor의 구분

함수 객체를 생성할때 함수 정의 방식에 따라 함수를
constructornon-constructor 로 구분한다.

constructor : 함수 선언문, 함수 표현식, 클래스(클래스도 함수다)
non-constructor : 메서드(ES5 메서드 축약표현), 화살표 함수

// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo() {}
const bar = function() {};

// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수다.
// 이는 함수로 메서드로 인정하지 않는다.
const baz = {
  x : function() {}
};

// 일반 함수로 정의된 함수만이 constructor다.
new foo(); // foo {}
new bar(); // bar {}
new baz.x(); // x {}

// 화살표 함수 정의
const arrow = () => {}

new arrow(); // TypeError: arrow is not a constructor

// 메서드 정의: ES6의 메서드 축약 표현만 메서드로 인정한다.
const obj = {
  x() {}
};

new obj.x(); // TypeError: obj.x is not a constructor

주의할점은 생성자 함수로서 호출될 것을 기대하고
정의하지 않은 일반 함수(callable 이면서 constructor)에
new 연산자를 붙여 호출하면 생성자 함수처럼 동작할 수도 있다.

function foo () {}

// 일반함수로서의 호출, [[call]]이 호출된다.
foo();

// 생성자함수로서의 호출, 이때 [[Construct]]를 갖지 않으면 에러 발생
new foo();

new 연산자

생성자 함수를 new 연산자 없이 호출하면 일반 함수로 호출된다.
이때 함수 내부의 this는 전역객체를 가리킨다.

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

const circle = Circle(5);
console.log(circle); // undefined

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

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

new.target

생성자 함수가 new 연산자 없이 사용되는 경우를 막기 위해 파스칼 케이스 컨벤션을
사용한다고 해도 실수는 발생할 수 있다.

이를 방지하기 위해 ES6에서 new.target을 지원한다.

new.target은 this와 유사하게 constructor인 모든 함수 내부에서
암묵적인 지역 변수와 같이 사용되며 메타 프로퍼티라고 부른다.

함수 내부에서 new.target을 사용하면
new 연산자를 사용해서 호출했는지 알 수 있다.
참고로 IE에서는 지원하지 않는다.

생성자 함수가 new 와 함께 호출 되었으면 new.target의 값은 함수 자신이고
그렇지 않은 경우 undefined이다.

아래는 활용 예시이다.

function Circle(radius) {
  if(!new.target) 
    return new Circle(radius);

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

// new 연산자 없이 생성자 함수를 호출하여도 new.target을 통해 
// 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter(0);

IE에서는 new.target을 지원하지 않기 때문에 다음과 같이 사용한다.

function Circle(radius) {
  
  // 이 함수가 new 연산자와 함께 호출되지 않았다면 
  // this는 window 이다.
  // 이 때 new 연산자와 함께 호출할 수 있도록 생성자 함수 호출을 반환한다.
  if(!(this instanceof Circle))
    return new Circle(radius));

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

// new 연산자 없이 생성자 함수를 호출하여도 new.target을 통해 
// 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter(0);

대부분의 빌트인 생성자함수
(Object, Number, Boolean, Function, Array, Date, RegExp, Promise 등)
new 연산자와 함께 호출되었는지 확인한 후
적절한 값을 반환한다.

하지만 String, Number, Boolean 생성자 함수는
new 생성자 함수와 함께 호출했을 때, String, Number, Boolean 객체를 생성하여
반환하지만 new 연산자 없이 호출하면 문자열, 숫자, 불리언 값을 반환한다.

이를 이용해서 데이터 타입을 변환하기도 한다.

profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글