티스토리 뷰

9.2 Class inheritance

The "extends" keyword

상속의 메커니즘은 자바와 크게 다르지 않은 것 같다.

class Animal {
  constructor(name) {
    this.speed = 0;
    this.name = name;
  }
  run(speed) {
    this.speed = speed;
    alert(`${this.name} 은/는 속도 ${this.speed}로 달립니다.`);
  }
  stop() {
    this.speed = 0;
    alert(`${this.name} 이/가 멈췄습니다.`);
  }
}

let animal = new Animal("동물");

// --------------------------

class Rabbit extends Animal {
  hide() {
    alert(`${this.name} 이/가 숨었습니다!`);
  }
}

let rabbit = new Rabbit("흰 토끼");

rabbit.run(5); // 흰 토끼 은/는 속도 5로 달립니다.
rabbit.hide(); // 흰 토끼 이/가 숨었습니다!
  • rabbit에 run 이 존재하는지 확인
  • rabbit의 prototype에 run이 존재하는지 확인
  • rabbit이 상속한 Animal의 prototype에 run이 존재하는지 확인 => 수행

위 순서로 동작한다. prototype을 건너뛰어서 정확하게 이해는 안 되지만, 하위 클래스에서 메서드를 찾아가는 과정은 자바와 비슷하다.

차이점은 표현식이 가능하다.

function f(phrase) {
  return class {
    sayHi() { alert(phrase) }
  }
}

class User extends f("Hello") {}

new User().sayHi(); // Hello

overriding a method

자바와 비슷하다.

class Animal {

  constructor(name) {
    this.speed = 0;
    this.name = name;
  }

  run(speed) {
    this.speed = speed;
    alert(`${this.name}가 속도 ${this.speed}로 달립니다.`);
  }

  stop() {
    this.speed = 0;
    alert(`${this.name}가 멈췄습니다.`);
  }

}

class Rabbit extends Animal {
  hide() {
    alert(`${this.name}가 숨었습니다!`);
  }

  stop() {
    super.stop(); // 부모 클래스의 stop을 호출해 멈추고,
    this.hide(); // 숨습니다.
  }
}

let rabbit = new Rabbit("흰 토끼");

rabbit.run(5); // 흰 토끼가 속도 5로 달립니다.
rabbit.stop(); // 흰 토끼가 멈췄습니다. 흰 토끼가 숨었습니다!

overriding constructor

하위 클래스에서 생성자를 만들 때는 꼭 super()를 통해 상위 클래스의 생성자를 호출해주어야 한다. 이 부분도 자바와 비슷하다.

class Animal {

  constructor(name) {
    this.speed = 0;
    this.name = name;
  }

  // ...
}

class Rabbit extends Animal {

  constructor(name, earLength) {
    super(name);
    this.earLength = earLength;
  }

  // ...
}

// 이제 에러 없이 동작합니다.
let rabbit = new Rabbit("흰 토끼", 10);
alert(rabbit.name); // 흰 토끼
alert(rabbit.earLength); // 10

Overriding class fields: a tricky note (어려운 내용.. 추후 살펴보기)

Super: internals, [[HomeObject]] (마찬가지로 어려움 추후 다시 살펴보기)

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday