Post

[모던 자바스크립트 Deep Dive]25장 클래스

25.1 클래스는 프로토타입의 문법적 설탕인가?

  • 자바스크립트 ⇒ 프로토타입 기반 객체지향 언어 ⇒ 클래스가 필요 없는 객체지향 언어
  • 클래스
    • ES6에서 도입
    • 클래스 기반 객체지향 프로그래밍과 비슷한 객체 생성 매커니즘 제공
    • 생성자 함수보다 엄격
    • 생성자 함수에서 제공하지 않는 기능 제공
  • 클래스와 생성자 함수의 차이점

    클래스생성자 함수
    new 연산자 없이 호출하면 에러 발생new 연산자 없이 호출하면 일반 함수로서 호출
    상속을 지원하는 extends와 super 키워드 제공extends와 super 키워드 지원 안 함
    호이스팅이 발생하지 않는 것처럼 동작함수 선언문으로 정의 → 함수 호이스팅 발생
    함수 표현식으로 정의 → 변수 호이스팅 발생
    암묵적으로 strict mode가 지정되어 실행
    strict mode 해제 불가
    암묵적 strict mode 지정 X
    • 또한 클래스의 constructor, 프로토타입 메서드, 정적 메서드는 [[Enumerable]] 값이 false이기 때문에 열거되지 않는다.

결론적으로, 클래스는 문법적 설탕이 아닌 새로운 객체 생성 매커니즘이다.

25.2 클래스 정의

  • class 키워드를 사용해 클래스 정의
  • 이름은 일반적으로 파스칼 케이스 사용
  • 표현식으로 정의 가능 ⇒ 클래스는 값으로 사용할 수 있는 일급 객체

    1
    2
    3
    4
    5
    
    // 익명 클래스 표현식
    const Person = class {};
    
    // 기명 클래스 표현식
    const Person = class MyClass {};
    
    • 이름은 옵션
  • 클래스는 값으로 사용할 수 있는 일급 객체
    • 그래서 표현식으로 정의할 수 있던 것
    • 일급 객체 특징
      • 무명의 리터럴로 생성 가능, 즉 런타임에 생성 가능
      • 변수나 자료구조에 저장 가능
      • 함수의 매개변수에 전달 가능
      • 함수의 반환값으로 사용 가능
  • 클래스 몸체에는 다음 세 가지 종류의 메서드만 정의 가능

    1. constructor
    2. 프로토타입 메서드
    3. 정적 메서드
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    class Person {
      // 생성자
      constructor(name) {
        // 인스턴스 생성 및 초기화
        this.name = name; // name 프로퍼티는 public하다.
      }
    
      // 프로토타입 메서드
      sayHi() {
        console.log(`Hi! My name is ${this.name}`);
      }
    
      // 정적 메서드
      static sayHello() {
        console.log("Hello!");
      }
    }
    
    // 인스턴스 생성
    const me = new Person("Lee");
    
    // 인스턴스의 프로퍼티 참조
    console.log(me.name); // Lee
    // 프로토타입 메서드 호출
    me.sayHi(); // Hi! My name is Lee
    // 정적 메서드 호출
    Person.sayHello(); // Hello!
    

25.3 클래스 호이스팅

  • 클래스는 함수로 평가
  • 함수 선언문처럼 런타임 이전에 평가되어 함수 객체 생성
    • 이 함수 객체는 생성자 함수로 호출할 수 있는 constructor
    • 생성자 함수와 프로토타입은 쌍으로 존재하므로 프로토타입도 이때 함께 생성
  • 클래스는 클래스 정의 이전에 참조 불가

    1
    2
    3
    4
    5
    
    console.log(Person);
    // ReferenceError: Cannot access 'Person' before initialization
    
    // 클래스 선언문
    class Person {}
    
  • 클래스는 클래스 선언문 이전에 일시적 사각지대(TDZ)에 빠져 호이스팅이 발생하지 않는 것처럼 동작

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    const Person = "";
    
    {
      // 호이스팅이 발생하지 않는다면 ''이 출력되어야 한다.
      console.log(Person);
      // ReferenceError: Cannot access 'Person' before initialization
    
      // 클래스 선언문
      class Person {}
    }
    

25.4 인스턴스 생성

  • 클래스는 생성자 함수 ⇒ new 연산자와 함께 호출되어 인스턴스 생성

    • 클래스를 new 연산자 없이 호출하면 에러 발생
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    class Person {}
    
    // 인스턴스 생성
    const me = new Person();
    console.log(me); // Person {}
    
    // 클래스를 new 연산자 없이 호출하면 타입 에러가 발생한다.
    const you = Person();
    // TypeError: Class constructor Foo cannot be invoked without 'new'
    
  • 클래스 표현식으로 정의된 클래스는 식별자로 인스턴스 생성

    • 기명 클래스 표현식의 클래스 이름을 사용하면 에러 발생
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    const Person = class MyClass {};
    
    // 함수 표현식과 마찬가지로 클래스를 가리키는 식별자로 인스턴스를 생성해야 한다.
    const me = new Person();
    
    // 클래스 이름 MyClass는 함수와 동일하게 클래스 몸체 내부에서만 유효한 식별자다.
    console.log(MyClass); // ReferenceError: MyClass is not defined
    
    const you = new MyClass(); // ReferenceError: MyClass is not defined
    

25.5 메서드

  • 클래스 몸체에는 메서드만 선언 가능
  • 클래스 몸체에는 다음 세 가지 종류의 메서드만 정의 가능
    1. constructor
    2. 프로토타입 메서드
    3. 정적 메서드

25.5.1 constructor

1
2
3
4
5
6
7
class Person {
  // 생성자
  constructor(name) {
    // 인스턴스 생성 및 초기화
    this.name = name;
  }
}
  • 인스턴스를 생성하고 초기화하는 메서드
    • 메서드로 해석되지 않고 함수 객체 코드의 일부가 된다.
  • constructor라는 이름은 변경 불가
  • 클래스는 인스턴스를 생성하는 생성자 함수다.
    • prototype 프로퍼티가 가리키는 프로토타입 객체의 contructor 프로퍼티는 클래스 자신을 가리킨다. class
  • constructor 내부에서 this에 추가한 프로퍼티는 인스턴스 프로퍼티가 된다. class2
    • constructor 내부에서 this는 클래스가 생성한 인스턴스를 가리킨다.

생성자 함수와의 차이점

  • constructor는 클래스 내에 최대 한 개 존재
  • constructor는 생략 불가

    1
    2
    3
    4
    5
    6
    7
    8
    
    class Person {
      // constructor를 생략하면 다음과 같이 빈 constructor가 암묵적으로 정의된다.
      constructor() {}
    }
    
    // 빈 객체가 생성된다.
    const me = new Person();
    console.log(me); // Person {}
    
    • 생략하면 암묵적으로 빈 constructor가 암묵적으로 정의된다.
  • constructor 내부에서 this에 인스턴스 프로퍼티를 추가

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    class Person {
      constructor() {
        // 고정값으로 인스턴스 초기화
        this.name = "Lee";
        this.address = "Seoul";
      }
    }
    
    // 인스턴스 프로퍼티가 추가된다.
    const me = new Person();
    console.log(me); // Person {name: "Lee", address: "Seoul"}
    
  • 매개변수를 이용하여 클래스 외부에서 인스턴스 프로퍼티 초기값을 전달

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    class Person {
      constructor(name, address) {
        // 인수로 인스턴스 초기화
        this.name = name;
        this.address = address;
      }
    }
    
    // 인수로 초기값을 전달한다. 초기값은 constructor에 전달된다.
    const me = new Person("Lee", "Seoul");
    console.log(me); // Person {name: "Lee", address: "Seoul"}
    
  • constructor는 별도의 반환문을 생략해야 한다(생성자 함수도 마찬가지).

    • this가 아닌 객체를 반환하면 return문에 명시한 객체가 반환된다.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      
      class Person {
        constructor(name) {
          this.name = name;
      
          // 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
          return {};
        }
      }
      
      // constructor에서 명시적으로 반환한 빈 객체가 반환된다.
      const me = new Person("Lee");
      console.log(me); // {}
      
    • 명시적으로 원시값을 반환하면 이를 무시하고 암묵적으로 this를 반환한다.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      
      class Person {
        constructor(name) {
          this.name = name;
      
          // 명시적으로 원시값을 반환하면 암묵적으로 this가 반환된다.
          return 100;
        }
      }
      
      const me = new Person("Lee");
      console.log(me); // Person { name: "Lee" }
      

25.5.2 프로토타입 메서드

  • 생성자 함수에선 명시적으로 프로토타입에 메서드를 추가해 프로토타입 메서드를 생성

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    // 생성자 함수
    function Person(name) {
      this.name = name;
    }
    
    // 프로토타입 메서드
    Person.prototype.sayHi = function () {
      console.log(`Hi! My name is ${this.name}`);
    };
    
    const me = new Person("Lee");
    me.sayHi(); // Hi! My name is Lee
    
  • 클래스 몸체에 정의한 메서드는 기본적으로 프로토타입 메서드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    class Person {
      // 생성자
      constructor(name) {
        // 인스턴스 생성 및 초기화
        this.name = name;
      }
    
      // 프로토타입 메서드
      sayHi() {
        console.log(`Hi! My name is ${this.name}`);
      }
    }
    
    const me = new Person("Lee");
    me.sayHi(); // Hi! My name is Lee
    
  • 생성자 함수처럼 클래스가 생성한 인스턴스도 프로토타입 체인의 일원

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    // me 객체의 프로토타입은 Person.prototype이다.
    Object.getPrototypeOf(me) === Person.prototype; // -> true
    me instanceof Person; // -> true
    
    // Person.prototype의 프로토타입은 Object.prototype이다.
    Object.getPrototypeOf(Person.prototype) === Object.prototype; // -> true
    me instanceof Object; // -> true
    
    // me 객체의 constructor는 Person 클래스다.
    me.constructor === Person; // -> true
    
    • 클래스는 생성자 함수처럼 프로토타입 기반의 객체 생성 메커니즘이다.

25.5.3 정적 메서드

  • 정적 메서드: 인스턴스를 생성하지 않아도 호출할 수 있는 메서드

    • 생성자 함수에서의 정적 메서드 생성

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      
      // 생성자 함수
      function Person(name) {
        this.name = name;
      }
      
      // 정적 메서드
      Person.sayHi = function () {
        console.log("Hi!");
      };
      
      // 정적 메서드 호출
      Person.sayHi(); // Hi!
      
  • 클래스에서는 메서드에 static 키워드를 붙이면 정적 메서드가 된다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    class Person {
      // 생성자
      constructor(name) {
        // 인스턴스 생성 및 초기화
        this.name = name;
      }
    
      // 정적 메서드
      static sayHi() {
        console.log("Hi!");
      }
    }
    
  • 정적 메서드는 클래스로 호출한다.
    1
    2
    3
    
    // 정적 메서드는 클래스로 호출한다.
    // 정적 메서드는 인스턴스 없이도 호출할 수 있다.
    Person.sayHi(); // Hi!
    
  • 인스턴스의 프로토타입 체인에는 클래스가 존재하지 않기 때문에 인스턴스로는 정적 메서드를 호출할 수 없다.
    1
    2
    3
    
    // 인스턴스 생성
    const me = new Person("Lee");
    me.sayHi(); // TypeError: me.sayHi is not a function
    

25.5.4 정적 메서드와 프로토타입 메서드의 차이

  1. 속해 있는 프로토타입 체인이 다르다.
  2. 정적 메서드는 클래스, 프로로타입 메서드는 인스턴스로 호출한다.
  3. 정적 메서드는 인스턴스 프로퍼티 참조 불가, 프로토타입 메서드는 인스턴스 프로퍼티 참조 가능

this 바인딩

  • 정적 메서드 내부의 this는 클래스를 가리킨다.
    • this를 사용하지 않는 메서드는 정적 메서드로 정의하는 것이 좋다.
  • 프로토타입 메서드 내부의 this는 프로토타입 메서드를 호출한 인스턴스를 가리킨다.
    • 메서드 내부에서 인스턴스 프로퍼티를 참조한다면 프로토타입 메서드로 정의해야 한다.

정적 메서드 응용

  • 정적 메서드는 애플리케이션 전역에서 사용할 유틸리티 함수를 구조화할 때 유용하다.

클래스 또는 생성자 함수를 네임스페이스로 사용하여 정적 메서드를 모아놓으면,

  1. 이름 충돌 가능성을 줄이고
  2. 관련 함수를 구조화할 수 있는

효과를 가진다.

1
2
3
4
5
6
// 표준 빌트인 객체가 정적 메서드를 사용해 구조화한 예시
Math.max(1, 2, 3); // -> 3
Number.isNaN(NaN); // -> true
JSON.stringify({ a: 1 }); // -> "{"a":1}"
Object.is({}, {}); // -> false
Reflect.has({ a: 1 }, "a"); // -> true

25.5.5 클래스에서 정의한 메서드의 특징

  1. function 키워드를 생략한 메서드 축약 표현 사용
  2. 객체 리터럴과 다르게, 메서드 정의 시 콤마 필요 없음
  3. 암묵적으로 strict mode로 실행
  4. 열거 불가
    1. [[Enumerable]]의 값이 false
  5. non-constructor
    1. 내부 메서드 [[Construct]]를 갖지 않음
    2. new 연산자와 함께 호출 불가

25.6 클래스의 인스턴스 생성 과정

1
2
3
4
5
6
7
8
9
10
11
12
13
class Person {
  // 생성자
  constructor(name) {
    // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
    console.log(this); // Person {}
    console.log(Object.getPrototypeOf(this) === Person.prototype); // true

    // 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
    this.name = name;

    // 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
  }
}

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

  1. new 연산자와 함께 클래스 호출
  2. 빈 객체, 즉 클래스가 생성한 인스턴스 생성
    1. 클래스의 prototype 프로퍼티가 가리키는 객체를 인스턴스의 프로토타입으로 설정
    2. 인스턴스를 this에 바인딩

2. 인스턴스 초기화

  1. constructor 내부 코드가 실행되어 인스턴스 초기화
    1. 인스턴스에 프로퍼티 추가
    2. 인수로 전달받은 초기값으로 인스턴스 프로퍼티 값을 초기화
  2. 만약 constructor가 생략되었다면 이 과정도 생략

3. 인스턴스 반환

  1. 완성된 인스턴스가 바인딩된 this를 암묵적으로 반환

25.7 프로퍼티

25.7.1 인스턴스 프로퍼티

  • constructor 내부에서 정의한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    class Person {
      constructor(name) {
        // 인스턴스 프로퍼티
        this.name = name;
      }
    }
    
    const me = new Person("Lee");
    console.log(me); // Person {name: "Lee"}
    
  • 인스턴스 프로퍼티는 언제나 public하다.

25.7.2 접근자 프로퍼티

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  // fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
  // getter 함수
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  // setter 함수
  set fullName(name) {
    [this.firstName, this.lastName] = name.split(" ");
  }
}

const me = new Person("Ungmo", "Lee");

// 데이터 프로퍼티를 통한 프로퍼티 값의 참조.
console.log(`${me.firstName} ${me.lastName}`); // Ungmo Lee

// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면 setter 함수가 호출된다.
me.fullName = "Heegun Lee";
console.log(me); // {firstName: "Heegun", lastName: "Lee"}

// 접근자 프로퍼티를 통한 프로퍼티 값의 참조
// 접근자 프로퍼티 fullName에 접근하면 getter 함수가 호출된다.
console.log(me.fullName); // Heegun Lee

// fullName은 접근자 프로퍼티다.
// 접근자 프로퍼티는 get, set, enumerable, configurable 프로퍼티 어트리뷰트를 갖는다.
console.log(Object.getOwnPropertyDescriptor(Person.prototype, "fullName"));
// {get: ƒ, set: ƒ, enumerable: false, configurable: true}
  • 자체적으로 값을 갖지 않음
    • 프로퍼티 어트리뷰트 [[Value]]를 갖지 않는다.
  • 접근자 함수(accessor function)로 구성
    • getter/setter 함수라고도 한다.
  • getter와 setter는 호출하는 것이 아니라 프로퍼티처럼 참조한다.
    • 참조 시 내부적으로 getter/setter가 호출된다.
  • getter는 반드시 무언가를 반환해야 한다.
  • setter는 반드시 매개변수가 있어야 한다.
    • setter는 단 하나의 값만 할당받기 때문에 단 하나의 매개변수만 선언 가능
  • 클래스의 접근자 프로퍼티는 메서드처럼 프로토타입의 프로퍼티가 된다. Untitled

25.7.3 클래스 필드 정의 제안

  • 클래스 필드(필드 또는 멤버): 클래스 기반 객체지향 언어에서 클래스가 생성할 인스턴스의 프로퍼티
  • 클래스 기반 객체지향 언어인 자바의 경우 클래스 필드에 다음과 같은 특징이 있다.
    1. 클래스 필드를 클래스 몸체에 this 없이 선언할 수 있다.
    2. this를 생략해도 클래스 필드를 참조할 수 있다.
    3. this는 클래스 필드임을 명확하게 하기 위해 주로 사용한다.
  • 반면 자바스크립트는 클래스 몸체에 메서드만 선언할 수 있었다.

Class field declarations

새로운 표준 사양으로 승급될 예정이며, 최신 브라우저와 Node.js에는 이미 구현되어 있다.

  • 클래스 필드를 클래스 몸체에 정의할 수 있다.

    1
    2
    3
    4
    5
    6
    7
    
    class Person {
      // 클래스 필드 정의
      name = "Lee";
    }
    
    const me = new Person();
    console.log(me); // Person {name: "Lee"}
    
  • 클래스 몸체 내에 클래스 필드를 정의하는 경우 this 바인딩 불가
    • this는 클래스의 constructor와 메서드 내에서만 유효
      1
      2
      3
      4
      
      class Person {
      // this에 클래스 필드를 바인딩해서는 안된다.
      this.name = ''; // SyntaxError: Unexpected token '.'
      }
      
  • 클래스 필드를 참조하는 경우 반드시 this를 사용해야 한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    class Person {
      // 클래스 필드
      name = "Lee";
    
      constructor() {
        console.log(name); // ReferenceError: name is not defined
      }
    }
    
    new Person();
    
  • 클래스 필드에 초기값을 할당하지 않으면 undefined를 갖는다.

    1
    2
    3
    4
    5
    6
    7
    
    class Person {
      // 클래스 필드를 초기화하지 않으면 undefined를 갖는다.
      name;
    }
    
    const me = new Person();
    console.log(me); // Person {name: undefined}
    
  • 외부 값으로 클래스 필드를 초기화할 땐 constructor에서 클래스 필드를 초기화해야 한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    class Person {
      name; // 작성할 필요 없다.
    
      constructor(name) {
        // 클래스 필드 초기화.
        this.name = name;
      }
    }
    
    const me = new Person("Lee");
    console.log(me); // Person {name: "Lee"}
    
    • 이때 초기화한 클래스 필드에 해당하는 프로퍼티가 없다면 자동 추가하기 때문에 constructor 밖에서 클래스 필드를 정의할 필요 없다.
  • 함수는 일급 객체 ⇒ 클래스 필드에 함수 할당 가능 ⇒ 클래스 필드로 메서드 정의 가능

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    class Person {
      // 클래스 필드에 문자열을 할당
      name = "Lee";
    
      // 클래스 필드에 함수를 할당
      getName = function () {
        return this.name;
      };
      // 화살표 함수로 정의할 수도 있다.
      // getName = () => this.name;
    }
    
    const me = new Person();
    console.log(me); // Person {name: "Lee", getName: ƒ}
    console.log(me.getName()); // Lee
    
    • 모든 클래스 필드는 인스턴트 프로퍼티가 되므로 클래스 필드에 함수 할당은 권장하지 않음

25.7.4 private 필드 정의 제안

새로운 표준 사양으로 승급될 예정이며, 최신 브라우저와 Node.js에는 이미 구현되어 있다.

  • private 필드 선두에 #을 붙이며, 참조할 때도 #을 붙인다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    class Person {
      // private 필드 정의
      #name = "";
    
      constructor(name) {
        // private 필드 참조
        this.#name = name;
      }
    }
    
    const me = new Person("Lee");
    
    // private 필드 #name은 클래스 외부에서 참조할 수 없다.
    console.log(me.#name);
    // SyntaxError: Private field '#name' must be declared in an enclosing class
    
  • private 필드는 클래스 내부에서만 참조할 수 있다.
  • 접근자 프로퍼티를 통해 간접적으로 접근할 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    class Person {
      // private 필드 정의
      #name = "";
    
      constructor(name) {
        this.#name = name;
      }
    
      // name은 접근자 프로퍼티다.
      get name() {
        // private 필드를 참조하여 trim한 다음 반환한다.
        return this.#name.trim();
      }
    }
    
    const me = new Person(" Lee ");
    console.log(me.name); // Lee
    
  • private 필드는 클래스 몸체에 정의해야 한다.
    1
    2
    3
    4
    5
    6
    7
    
    class Person {
      constructor(name) {
        // private 필드는 클래스 몸체에서 정의해야 한다.
        this.#name = name;
        // SyntaxError: Private field '#name' must be declared in an enclosing class
      }
    }
    

25.7.5 static 필드 정의 제안

새로운 표준 사양으로 승급될 예정이며, 최신 브라우저와 Node.js에는 이미 구현되어 있다.

  • static 키워드를 사용해 static public/private 필드를 정의할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyMath {
  // static public 필드 정의
  static PI = 22 / 7;

  // static private 필드 정의
  static #num = 10;

  // static 메서드
  static increment() {
    return ++MyMath.#num;
  }
}

console.log(MyMath.PI); // 3.142857142857143
console.log(MyMath.increment()); // 11

25.8 상속에 의한 클래스 확장

25.8.1 클래스 상속과 생성자 함수 상속

  • 프로토타입 기반 상속: 프로토타입 체인을 통해 다른 객체의 자산을 상속받음
  • 상속에 의한 클래스 확장: 기존 클래스를 상속받아 새로운 클래스를 확장하여 정의

    • 클래스는 상속자 함수와 달리 기존 클래스 확장을 위한 문법 제공
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    class Animal {
      constructor(age, weight) {
        this.age = age;
        this.weight = weight;
      }
    
      eat() {
        return "eat";
      }
    
      move() {
        return "move";
      }
    }
    
    // 상속을 통해 Animal 클래스를 확장한 Bird 클래스
    class Bird extends Animal {
      fly() {
        return "fly";
      }
    }
    
    const bird = new Bird(1, 5);
    
    console.log(bird); // Bird {age: 1, weight: 5}
    console.log(bird instanceof Bird); // true
    console.log(bird instanceof Animal); // true
    
    console.log(bird.eat()); // eat
    console.log(bird.move()); // move
    console.log(bird.fly()); // fly
    

25.8.2 extends 키워드

  • extends 키워드를 사용해 상속받을 클래스를 정의한다.

    • 서브클래스(파생 클래스, 자식 클래스): 상속을 통해 확장된 클래스
    • 수퍼클래스(베이스 클래스, 부모 클래스): 서브클래스에 상속된 클래스
    1
    2
    3
    4
    5
    
    // 수퍼(베이스/부모)클래스
    class Base {}
    
    // 서브(파생/자식)클래스
    class Derived extends Base {}
    
  • 수퍼클래스와 서브클래스는 인스턴스의 프로토타입 체인, 클래스 간 프로토타입 체인을 함께 생성

    • 클래스도 프로토타입을 통해 상속 관계 구현
    • 프로토타입 메서드, 정적 메서드 모두 상속 가능

25.8.3 동적 상속

  • 클래스는 extends 키워드를 사용해 생성자 함수를 상속받아 확장할 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    // 생성자 함수
    function Base(a) {
      this.a = a;
    }
    
    // 생성자 함수를 상속받는 서브클래스
    class Derived extends Base {}
    
    const derived = new Derived(1);
    console.log(derived); // Derived {a: 1}
    
  • [[Construct]] 내부 메서드를 갖는 함수 객체로 평가되는 모든 표현식을 사용 가능

    • 이를 통해 동적으로 상속받을 대상을 결정할 수 있다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    function Base1() {}
    
    class Base2 {}
    
    let condition = true;
    
    // 조건에 따라 동적으로 상속 대상을 결정하는 서브클래스
    class Derived extends (condition ? Base1 : Base2) {}
    
    const derived = new Derived();
    console.log(derived); // Derived {}
    
    console.log(derived instanceof Base1); // true
    console.log(derived instanceof Base2); // false
    

25.8.4 서브클래스의 constructor

  • 서브클래스에서 constructor를 생략하면 다음과 같이 constructor가 암묵적으로 정의됨
    1
    
    constructor(...args) { super(...args); }
    
    • args: new 연산자와 함께 클래스 호출 시 전달한 인수 리스트
    • super(): 수퍼클래스의 constructor를 호출해 인스턴스를 생성
  • 수퍼클래스와 서브클래스 모두 constructor를 생략하면 빈 객체 생성

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    class Base {}
    
    class Derived extends Base {}
    
    // 이는 암묵적으로 다음과 같이 정의된다.
    
    class Base {
      constructor() {}
    }
    
    class Derived extends Base {
      constructor() {
        super();
      }
    }
    
    const derived = new Derived();
    console.log(derived); // Derived {}
    

25.8.5 super 키워드

  • super 호출 ⇒ 수퍼클래스의 constructor 호출
  • super 참조 ⇒ 수퍼클래스의 메서드 호출

super 호출

  • super를 호출하면 수퍼클래스의 constructor를 호출한다.
  • 서브클래스의 constructor를 생략하고 싶은 경우

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    // 수퍼클래스
    class Base {
      constructor(a, b) {
        this.a = a;
        this.b = b;
      }
    }
    
    // 서브클래스
    class Derived extends Base {
      // 다음과 같이 암묵적으로 constructor가 정의된다.
      // constructor(...args) { super(...args); }
    }
    
    const derived = new Derived(1, 2);
    console.log(derived); // Derived {a: 1, b: 2}
    
  • 명시적으로 super를 호출하는 경우

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    // 수퍼클래스
    class Base {
      constructor(a, b) {
        // ④
        this.a = a;
        this.b = b;
      }
    }
    
    // 서브클래스
    class Derived extends Base {
      constructor(a, b, c) {
        // ②
        super(a, b); // ③
        this.c = c;
      }
    }
    
    const derived = new Derived(1, 2, 3); // ①
    console.log(derived); // Derived {a: 1, b: 2, c: 3}
    
  • 주의사항

    1. 서브클래스에서 constructor를 생략하지 않는 경우 서브클래스의 constructor에 반드시 super 호출

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      
      class Base {}
      
      class Derived extends Base {
        constructor() {
          // ReferenceError: Must call super constructor in derived class
          // before accessing 'this' or returning from derived constructor
          console.log("constructor call");
        }
      }
      
      const derived = new Derived();
      
    2. 서브클래스의 constructor에서 super를 호출하기 전 this 참조 불가능

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      
      class Base {}
      
      class Derived extends Base {
        constructor() {
          // ReferenceError: Must call super constructor in derived class
          // before accessing 'this' or returning from derived constructor
          this.a = 1;
          super();
        }
      }
      
      const derived = new Derived(1);
      
    3. super는 반드시 서브클래스의 constructor에서만 호출

      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      class Base {
        constructor() {
          super(); // SyntaxError: 'super' keyword unexpected here
        }
      }
      
      function Foo() {
        super(); // SyntaxError: 'super' keyword unexpected here
      }
      

super 참조

  • 메서드 내에서 super 참조 시 수퍼클래스의 메서드 호출 가능
  • 서브클래스의 정적 메서드 내에서 수퍼클래스의 정적 메서드를 가리킬 수 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    // 수퍼클래스
    class Base {
      static sayHi() {
        return "Hi!";
      }
    }
    
    // 서브클래스
    class Derived extends Base {
      static sayHi() {
        // super.sayHi는 수퍼클래스의 정적 메서드를 가리킨다.
        return `${super.sayHi()} how are you doing?`;
      }
    }
    
    console.log(Derived.sayHi()); // Hi! how are you doing?
    

super 참조의 자세한 과정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 수퍼클래스
class Base {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    return `Hi! ${this.name}`;
  }
}

// 서브클래스
class Derived extends Base {
  sayHi() {
    // super.sayHi는 수퍼클래스의 프로토타입 메서드를 가리킨다.
    return `${super.sayHi()}. how are you doing?`;
  }
}

const derived = new Derived("Lee");
console.log(derived.sayHi()); // Hi! Lee. how are you doing?

위 예제는 다음 예제와 동일하게 동작한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 수퍼클래스
class Base {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    return `Hi! ${this.name}`;
  }
}

class Derived extends Base {
  sayHi() {
    // __super는 Base.prototype을 가리킨다.
    const __super = Object.getPrototypeOf(Derived.prototype);
    return `${__super.sayHi.call(this)} how are you doing?`;
  }
}
  1. super는 자신을 참조하는 메서드가 바인딩 된 객체의 프로토타입을 가리킨다.
    1. 자신을 참조하는 메서드 → DerivedsayHi
    2. ~가 바인딩된 객체 → Derived.prototype
    3. ~의 프로토타입 → Base.prototype
  2. 따라서 super.sayHiBase.prototype.sayHi이다.
  3. Base.prototype.sayHi 메서드 → 프로토타입 메서드 → this는 인스턴스를 가리켜야 함
  4. Base.prototype.sayHi 메서드 내부의 thisBase.prototype
  5. 따라서 call 메서드를 사용해 this 전달

[[HomeObject]]

  • 메서드의 내부 슬롯 [[HomeObject]]은 자신을 바인딩하고 있는 객체를 가리킴
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    /*
    [[HomeObject]]는 메서드 자신을 바인딩하고 있는 객체를 가리킨다.
    [[HomeObject]]를 통해 메서드 자신을 바인딩하고 있는 객체의 프로토타입을 찾을 수 있다.
    예를 들어, Derived 클래스의 sayHi 메서드는 Derived.prototype에 바인딩되어 있다.
    따라서 Derived 클래스의 sayHi 메서드의 [[HomeObject]]는 Derived.prototype이고
    이를 통해 Derived 클래스의 sayHi 메서드 내부의 super 참조가
    Base.prototype으로 결정된다.
    따라서 super.sayHi는 Base.prototype.sayHi를 가리키게 된다.
    */
    super = Object.getPrototypeOf([[HomeObject]])
    
  • “자신을 참조하는 메서드가 바인딩된 객체의 프로토타입”을 찾을 때 이용
  • ES6의 메서드 축약 표현으로 정의된 함수만 내부 슬롯 [[HomeObject]]을 가짐
    1
    2
    3
    4
    5
    6
    7
    
    const obj = {
      // foo는 ES6의 메서드 축약 표현으로 정의한 메서드다. 따라서 [[HomeObject]]를 갖는다.
      foo() {},
      // bar는 ES6의 메서드 축약 표현으로 정의한 메서드가 아니라 일반 함수다.
      // 따라서 [[HomeObject]]를 갖지 않는다.
      bar: function () {},
    };
    
  • 객체 리터럴에서도 super 참조 사용 가능

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    const base = {
      name: "Lee",
      sayHi() {
        return `Hi! ${this.name}`;
      },
    };
    
    const derived = {
      __proto__: base,
      // ES6 메서드 축약 표현으로 정의한 메서드다. 따라서 [[HomeObject]]를 갖는다.
      sayHi() {
        return `${super.sayHi()}. how are you doing?`;
      },
    };
    
    console.log(derived.sayHi()); // Hi! Lee. how are you doing?
    

25.8.6 상속 클래스의 인스턴스 생성 과정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 수퍼클래스
class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }

  toString() {
    return `width = ${this.width}, height = ${this.height}`;
  }
}

// 서브클래스
class ColorRectangle extends Rectangle {
  constructor(width, height, color) {
    super(width, height);
    this.color = color;
  }

  // 메서드 오버라이딩
  toString() {
    return super.toString() + `, color = ${this.color}`;
  }
}

const colorRectangle = new ColorRectangle(2, 4, "red");
console.log(colorRectangle); // ColorRectangle {width: 2, height: 4, color: "red"}

// 상속을 통해 getArea 메서드를 호출
console.log(colorRectangle.getArea()); // 8
// 오버라이딩된 toString 메서드를 호출
console.log(colorRectangle.toString()); // width = 2, height = 4, color = red

1. 서브클래스의 super 호출

  • [[ConstructorKind]] 내부 슬롯
    • base 또는 derived를 값으로 가짐
    • 수퍼클래스와 서브클래스를 구분하기 위해 사용
    • 이를 통해 new 연산자와 함께 호출되었을 때 동작 구분
  • 서브클래스는 수퍼클래스에 인스턴트 생성을 위임
    • 따라서 서브클래스의 constructor에서 super 호출 필수
  • 서브클래스의 super 호출 과정
    1. 서브클래스를 new 연산자와 함께 호출
    2. 서브클래스 constructor 내부의 super 키워드 호출
    3. 수퍼클래스가 평가되어 생성된 함수 객체의 코드 실행 시작

2. 수퍼클래스의 인스턴스 생성과 this 바인딩

1
2
3
4
5
6
7
8
9
10
11
12
13
// 수퍼클래스
class Rectangle {
  constructor(width, height) {
    // 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩된다.
    console.log(this); // ColorRectangle {}
    // new 연산자와 함께 호출된 함수, 즉 new.target은 ColorRectangle이다.
    console.log(new.target); // ColorRectangle

    // 생성된 인스턴스의 프로토타입으로 ColorRectangle.prototype이 설정된다.
    console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype); // true
    console.log(this instanceof ColorRectangle); // true
    console.log(this instanceof Rectangle); // true
...
  1. 수퍼클래스의 constructor 내부 코드가 실행되기 전 암묵적으로 빈 객체 생성
  2. 이 빈 객체는 클래스가 생성한 인스턴스이며 this에 바인딩된다.
  3. new.target은 서브클래스를 가리킨다.
    1. new.target은 new 연산자와 함께 호출된 함수를 가리킴
    2. 따라서 인스턴스는 서브클래스가 생성한 것으로 처리
    3. 따라서 인스턴스의 프로토타입은 서브클래스의 prototype 프로퍼티가 가리키는 객체

3. 수퍼클래스의 인스턴스 초기화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 수퍼클래스
class Rectangle {
  constructor(width, height) {
    // 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩된다.
    console.log(this); // ColorRectangle {}
    // new 연산자와 함께 호출된 함수, 즉 new.target은 ColorRectangle이다.
    console.log(new.target); // ColorRectangle

    // 생성된 인스턴스의 프로토타입으로 ColorRectangle.prototype이 설정된다.
    console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype); // true
    console.log(this instanceof ColorRectangle); // true
    console.log(this instanceof Rectangle); // true

    // 인스턴스 초기화
    this.width = width;
    this.height = height;

    console.log(this); // ColorRectangle {width: 2, height: 4}
  }
...
  1. 수퍼클래스의 constructor 실행
  2. this에 바인딩되어 있는 인스턴스 초기화
    1. 인스턴스에 프로퍼티 추가
    2. 인수로 전달받은 초기값으로 초기화

4. 서브클래스 constructor로의 복귀와 this 바인딩

1
2
3
4
5
6
7
8
// 서브클래스
class ColorRectangle extends Rectangle {
  constructor(width, height, color) {
    super(width, height);

    // super가 반환한 인스턴스가 this에 바인딩된다.
    console.log(this); // ColorRectangle {width: 2, height: 4}
...
  1. super 호출 종료 → 제어흐름이 서브클래스 constructor로 이동
  2. super가 반환한 인스턴스가 this에 바인딩
    1. 따라서 super 호출 전 this 사용 불가

즉, super 호출이 인스턴스 생성과 this 바인딩을 모두 책임진다.

5. 서브클래스 인스턴스 초기화

  • 서브클래스 constructor에 기술된 인스턴스 초기화 실행
    • 인스턴스에 프로퍼티 추가
    • 인수로 전달받은 초기값으로 초기화

6. 인스턴스 반환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 서브클래스
class ColorRectangle extends Rectangle {
  constructor(width, height, color) {
    super(width, height);

    // super가 반환한 인스턴스가 this에 바인딩된다.
    console.log(this); // ColorRectangle {width: 2, height: 4}

    // 인스턴스 초기화
    this.color = color;

    // 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
    console.log(this); // ColorRectangle {width: 2, height: 4, color: "red"}
  }
...
  • 완성된 인스턴스가 바인딩 된 this를 암묵적으로 반환

25.8.7 표준 빌트인 생성자 함수 확장

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Array 생성자 함수를 상속받아 확장한 MyArray
// Array.prototype 메서드 사용 가능
class MyArray extends Array {
  // 중복된 배열 요소를 제거하고 반환한다: [1, 1, 2, 3] => [1, 2, 3]
  uniq() {
    return this.filter((v, i, self) => self.indexOf(v) === i);
  }

  // 모든 배열 요소의 평균을 구한다: [1, 2, 3] => 2
  average() {
    return this.reduce((pre, cur) => pre + cur, 0) / this.length;
  }
}

const myArray = new MyArray(1, 1, 2, 3);
console.log(myArray); // MyArray(4) [1, 1, 2, 3]

// MyArray.prototype.uniq 호출
console.log(myArray.uniq()); // MyArray(3) [1, 2, 3]
// MyArray.prototype.average 호출
console.log(myArray.average()); // 1.75
  • [[Construct]] 내부 메서드를 갖는 표준 빌트인 객체도 확장할 수 있다.
  • Array.prototype 메서드 중 map, filter와 같이 새로운 배열을 반환하는 메서드는 서브클래스의 인스턴스를 반환

    • 따라서 위 예시를 통해 다음과 같은 메서드 체니잉이 가능하다.
      1
      2
      3
      4
      5
      6
      7
      8
      
      // 메서드 체이닝
      // [1, 1, 2, 3] => [ 1, 1, 3 ] => [ 1, 3 ] => 2
      console.log(
        myArray
          .filter((v) => v % 2)
          .uniq()
          .average()
      ); // 2
      
    • 서브클래스의 인스턴스가 생성되는 것을 막기 위해 Symbol.species를 이용할 수 있다.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      
      // Array 생성자 함수를 상속받아 확장한 MyArray
      class MyArray extends Array {
        // 모든 메서드가 Array 타입의 인스턴스를 반환하도록 한다.
        static get [Symbol.species]() {
          return Array;
        }
      
        // 중복된 배열 요소를 제거하고 반환한다: [1, 1, 2, 3] => [1, 2, 3]
        uniq() {
          return this.filter((v, i, self) => self.indexOf(v) === i);
        }
      
        // 모든 배열 요소의 평균을 구한다: [1, 2, 3] => 2
        average() {
          return this.reduce((pre, cur) => pre + cur, 0) / this.length;
        }
      }
      
      const myArray = new MyArray(1, 1, 2, 3);
      
      console.log(myArray.uniq() instanceof MyArray); // false
      console.log(myArray.uniq() instanceof Array); // true
      
      // 메서드 체이닝
      // uniq 메서드는 Array 인스턴스를 반환하므로 average 메서드를 호출할 수 없다.
      console.log(myArray.uniq().average());
      // TypeError: myArray.uniq(...).average is not a function
      
This post is licensed under CC BY 4.0 by the author.