[JavaScript] 모던 자바스크립트 Deep Dive 17장 - 생성자 함수에 의한 객체 생성

2022. 7. 27. 18:22Web/JavaScript


17.1 Object 생성자 함수

new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다. 빈 객체를 생성한 이후 프로퍼티 또는 메서드를 추가하여 객체를 완성할 수 있다.

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

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

console.log(person); // { name: 'Eo', sayHello: [Function (anonymous)] }
person.sayHello(); // Hi! My name is Eo

 

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


17.2 생성자 함수


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

객체 생성 방식은 직관적이고 간편하지만 단 하나의 객체만 생성하기 때문에 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우 매번 같은 프로퍼티를 기술하야 하므로 비효율적이다.

 

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

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

객체를(인스턴스)를 생성하기 위한 템플릿(클래스)처럼 생성자 함수를 사용하여 프로퍼티 구조가 동일한 객체 여러 개를 간편하게 생성할 수 있다.

// 생성자 함수
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());
console.log(circle2.getDiameter());

 

new 연사자와 함께 생성자 함수를 호출하지 않으면 생성자 함수가 아니라 일반 함수로 동작

const circle3 = Circle(15);

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

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

 


this

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

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

생성자 함수의 역할: 인스턴스 생성과 생성된 인스턴스를 초기화(인스턴스 프로퍼티 추가 및 초기값 할당)

 

바인딩: 식별자와 값을 연결하는 과정

 

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

2. 인스턴스 초기화

3. 인스턴스 반환


17.2.6 new 연산자

 

new 연산자와 함께 호출하는 함수

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

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

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

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

// 일반 함수를 new 연산자와 함께 호출
inst = new createUser('Eo', 'admin');
// 함수가 생성한 객체를 반환한다.
console.log(inst); // { name: 'Eo', role: 'admin' }

 

new 연산자없이 호출하는 함수

// 생성자 함수
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(getDiameter()); // 10

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

17.2.7 new.target

생성자 함수가 new 연산자 없이 호출되는 것을 방지하기 위해 ES6에서는 new.target을 지원한다.

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

 

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 * radius;
    };
}

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