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

이번 17 장에서는 다양한 객체 생성 방식 중에서 생성자 함수를 사용하여 객체를 생성하는 방식을 살펴본다. 그리고 객체 리터럴을 사용하여 객체를 생성하는 방식과 생성자 함수를 사용하여 객체를 생성하는 방식과의 장단점을 살펴보자!

17.1 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: /}
person.sayHello(); // Hi! My name is Lee

17.2 생성자 함수

17.2.1 객체 리터럴에 의한 객체 생성 방식의 문제점
17.2.2 생성자 함수에 의한 객체 생성 방식의 장점
// 생성자 함수
function Circle(radius) {
    // 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
    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.Iog(circle2.getDiameter()); // 20

// new 연산자와 함께 호출하지 않으면 생성자 함수로 동작하지 않는다.
// 즉, 일반 함수로서 호출된다.
const circles = Circle(15);
// 일반 함수로서 호출된 Circle은 반환문이 없0므루 암묵적으로 undefine% 반환한다.
console.Iog(circle3); // undefined
// 일반 함수로서 호출된 Circle 내의 this는 전역 객체를 가리킨다.
console.log(radius); // 15
17.2.3 생성자 함수의 인스턴스 생성 과정
// 생성자 함수
function Circle(radius) {
    // 인스턴스 초기화
    this.radius = radius;
    this.getDiameter = function () {
        return 2 * this.radius;
    }
}
// 인스턴스 생성
const circlel = new Circle5; // 반지름이 5인 Circle 객체를 생성
인스턴스 생성과 this 바인딩
function Circleradius {
    // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
    console.logthis; // Circle {}
    this.radius = radius;
    this.getDiameter = function () {
        return 2 * this.radius;
    }
}
인스턴스 초기화
인스턴스 반환
function Circle(radius) {
    // 1. 암묵적으로 빈 객체가 생성되고 thisOfl 바인딩된다.
    // 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
    this.radius = radius;
    this.getDiameter = function () {
        return 2 * this.radius;
    }
    // 3. 암묵적으로 this를 반환한다.
    // 명시적으로 원시 값을 반환하면 원시 값 반환은 무시되고 암묵적으로 this가 반환된다.
    return 100;
}
// 인스턴스 생성. Circle 생성자 함수는 명시적으로 반환한 객체를 반환한다.
const circle = new Circle(l);
console.log(circle); // Circle {radius: 1, getDiameter: f}
17.2.4 내부 메서드 [[Call]]과 [[Construct]]
// 함수는 객체다.
function foo() {}
// 함수는 객체이므로 프로퍼티를 소유할 수 있다.
foo.prop = 10;
// 함수는 객체이므로 메서드를 소유할 수 있다.
foo.method = function () {
    console.log(this.prop);
}
foo.method(); // 10
function foo() {}
// 일반적인 함수로서 호출: [[Call]]이 호출된다.
foo();
// 생성자 함수로서 호출: [[Construct]]가 호출된다.
new foo();
17.2.5 constructor와 non-constructor의 구분
// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo() {}
const bar = function () {};
// 일반 함수로 정의된 함수만이 constructor다.
new foo(); // — foo {}
new bar(); // — bar {}
// 화살표 함수 정의
const arrow = () => {};
new arrow(); // TypeError: arrow is not a constructor
17.2.6 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(1 Lee', 'admin1);
// 함수가 생성한 객체를 반환한다.
console.log(inst); // {name: "Lee", role: "admin"}
17.2.7 new.target
// 생성자 함수
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(circle.getDiameter());

끝!