티스토리 뷰

Javascript

다형성과 다중 상속

mongoT 2020. 3. 1. 20:28

다형성이란 부모 클래스의 프로퍼티를 자식 클래스에서 다형적으로 가질 수 있음을 의미한다.

 

다형성

class Vehicle {
  constructor() {
    this.engines = 1;
  }

  iginition() {
    console.log("engine is up!");
  }

  drive() {
    this.iginition();
    console.log("Vehicle drive!");
  }
}

class Car extends Vehicle {
  constructor() {
      super();
      this.wheels=4;
  }

  drive(){
      console.log(this.wheels, 'Car drive!');
  }
}

class SpeedBoat extends Vehicle{
    constructor(){
        super();
        this.engines=2;
    }
    iginition(){
        console.log(this.engines, 'engine is up!');
    }
    pilot(){
        this.drive();
        console.log('SpeedBoat drive!');
    }
}

SpeedBoat클래스의 인스턴스에서 pilot()메서드를 호출하면 this.drive()에 의해 부모 클래스에 있는 drive() 메서드를 호출한다.

drive()에서는 또 다시 this.iginition()을 호출한다. 여기서 this.ignition()은 SpeadBoat의 iginiton()이다.

const speedBoat = new SpeedBoat();
speedBoat.iginition();
speedBoat.pilot();
// 2 engine is up!
// 2 engine is up!
// Vehicle drive!
// SpeedBoat drive!

const car = new Car();
car.drive();
// 4 Car drive!

Car인스턴스의 drive()는 drive()를 다시 재정의 하였기 때문에 부모 프로퍼티가 가려지고 결과적으로 다른 언어의 OOP처럼 overriding 된다.

다중 상속

 

자바스크립트는 다른 언어의 OOP와는 다른 점이 있다.

자바스크립트는 다중 상속을 지원하지 않는다.

상속할 때 부모 클래스의 프로퍼티들을 복사하지 않고 서로 연결이 된다는 것이다.

믹스인을 이용하면 다중 상속을 흉내 낼 수 있다.

믹스인(Mixin)은 자바스크립트에서 누락된 클래스 복사 기능을 흉내 낸 것이다.

 

Vehicle상속을 유지하면서 speedBoat에 있는 프로퍼티들을 쓰고 싶다면 

function mixin(sourceObj, targetObj) {
  for (let key in sourceObj) {
    // 타깃에 없는 프로퍼티만 복사한다.
    if (!(key in targetObj)) {
      targetObj[key] = sourceObj[key];
    }
  }
  return targetObj;
}

class라는 키워드의 특징 중 하나가 descriptor에서 enumerable: false로 기본 설정하기 때문에 mixin 하기 전에 mixin 하고 싶은 data property에 대해 enumerable을 true로 바꿔줘야 for...in 구문에서 순회할 수 있다.

Object.defineProperty(SpeedBoat.prototype, "pilot", {
  enumerable: true
});

let car = new Car();
car = mixin(SpeedBoat.prototype, car);
car.pilot();
// 4 Car drive!
// SpeedBoat drive!

이 mixin은 객체를 매개변수로 받지만 다중 상속처럼 보이려면 클래스로 받는게 더 좋을 테니까 클래스 버전으로 바꾸면

function mixin2(sourceClass, targetClass) {
  let sourceObj = sourceClass.prototype;
  let targetObj = targetClass.prototype;

  for (let key in sourceObj) {
    // 타깃에 없는 프로퍼티만 복사한다.
    if (!(key in targetObj)) {
      targetObj[key] = sourceObj[key];
    }
  }
}

사용도 간단하다.

mixin2(SpeedBoat, Car)

let car = new Car();
car.pilot();
// 4 Car drive!
// SpeedBoat drive!

 

참고문헌: You don't know JS - 카일 심슨

'Javascript' 카테고리의 다른 글

객체프로퍼티 나열  (0) 2020.03.01
iterator 와 generator  (0) 2020.03.01
Map과 Set  (0) 2020.03.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함