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

이재민·2023년 7월 7일
0

자바스크립트

목록 보기
14/17

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", sqyHello: f}

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

// String 생성자 함수에 의한 String rorcp todtjd
const str = new String('Lee');
console.log(typeof str); // object
console.log(str) // Lee

//Object, String 이외에도 Number, Boolean, Function, Array, Date, RegExp, Promise등이 있다

생성자 함수

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

직관적이고 간편하다. 하지만 하나의 객체만을 생성하므로 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우 매번 같은 프로퍼티를 기술해야 하는 번거로움이 있음

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

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

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

프로퍼티 구조가 동일한 객체 여러 개를 간편하게 생성할 수 있음.

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.log(circle2.getDiameter()); // 20

생성자 함수는 이름 그대로 객체를 생성하는 함수. 자바와 같은 클래스 기반 언어의 생성자와는 다르게 형식이 정해져 있는 것이 아니라 일반 함수와 동일한 방법으로 생성자 함수를 정의하고 new 연산자와 함께 호출하면 해당 함수는 생성자 함수로 동작.

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

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

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

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

생성자 함수의 역할은 인스턴스를 생성하는 것과 생성된 인스턴스를 초기화하는 것임.

  1. 인스턴스 생성과 this 바인딩 (런타임 이전에 실행)

  2. 인스턴스 초기화

  3. 인스턴스 반환

    함수 내부의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this를 암묵적으로 반환.

    function Circle(radius){
        //1. 암묵적으로 빈 객체가 생성되고 this에 바인딩
        //2. this에 바인딩되어 있는 인스턴스를 초기화
        
        this.radius = radius;
        this.getDiameter = function(){
            return 2 * this.radius
        };
        //3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환
        
        // return {}; 명식적으로 객체를 반환하면 암묵적인 this 반환이 무시
        // 하지만 명시적으로 원시 값을 반환하면 원시 값 반환은 무시되고 암묵적으로 this 반환
        // return 100;
    }
    // 인스턴스 생성. Circle 생성자 함수는 암묵적으로 this를 반환
    const circle1 = new Circle(1); 
    console.log(circle); // Circle {radius: 1, getDiameter: f}
    //console.log(circle); // {}

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

함수는 객체이지만 일반 객체와는 다름. 일반 객체는 호출할 수 없지만 함수는 호출할 수 있음.

함수가 일반 함수로서 호출되면 함수 객체의 내부 메서드 [[Call]]이 호출되고 new 연산자와 함께 생성자 함수로서 호출되며 내부 메서드 [[Construct]]가 호출.

function a(){}

// 일반적인 함수로서 호출. [[Call]]이 호출
a();

// 생성자 함수로서 호출. [[Construct]]이 호출
new a();

내부 메서드 [[Call]]을 갖는 함수 객체를 callable이라함. 내부 메서드 [[Construct]]의 유무에 따라 constructor, non-constructor이라 함

함수 객체는 callable이면서 constructor이거나 callable이면서 non-constructor임

constructor와 non-constructor의 구분

  • constructor : 함수 선언문, 함수 표현식, 클래스 (클래스도 함수)
  • non-constructor : 메서드(ES6 메서드 축약 표현), 화살표 함수
// 일반 함수 정의 : 함수 선언문, 함수 표현식
function a(){}
const b = function() {};
// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수. 메서드로 인정x
const ba = {
    x : function (){}
}

// 일반 함수로 정의된 함수만이 constructor.
new a(); // a{}
new b(); // b{}
new ba.x(); // x{}

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

new arrow = () => {}; // TypeError: arrow is not a constructor

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

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('Lee', 'addmin');
// 함수가 생성한 객체를 반환
console.log(inst) // {name: "Lee", role: "admin"}

반대로 new 연산자 없이 생성자 함수를 호출하면 일반 함수로 호출. [[Construct]]가 아니라 [[Call]]이 호출.

// 생성자 함수
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

new.target

new 연산자와 함께 생성자 람수로서 호출되면 함수 내부의 new.target은 함수 자신을 가르킴. new 연산자 없이 일반 함수로서 호출된 함수 내부의 new.target은 undefined임

// 생성자 함수
function Circle(radius){
    // 이 함수가 new 연산자와 함께 호출되지 않았다면 new.target은 undefined
    if(!new.target){
        // new 연산자와 함께 생성자 함수를 재귀 호출하여 생성된 인스턴스 반환.
        return new Circle(radius);
    }
    // new.target은 IE에서 지원하지 않음. new target을 사용할 수 없는 상황일 경우
    /* 스코프 세이프 생성자 패턴 사용
    if(!(this instanceof Circle)){
    	// 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());

참고

대부분의 빌트인 생성자 함수(Object, Number, Boolean, Function, Array, Date, RegExp, Promise 등)sms new연산자와 함께 호출되는지를 확인 후 적절한 값을 반환. new 연산자가 없어도 new연산자와 함께 호출했을 때와 동일하게 동작.

하지만 String, Number, Boolean은 new와 함께면 객체를 반환하지만, new 가 없으면 문자열, 숫자, 불리언 값을 반환

profile
안녕하세요

0개의 댓글