class / extends / super

future·2021년 1월 17일
0

JavaScript

목록 보기
6/10
post-thumbnail

지금까지 배운 prototype을 이용한 방법으로 상속의 기능을 구현할 때는 아래와 같다.

const Mufasa = function() {
  this.position = 'king';
}

Mufasa.prototype.deliver = function() {
  return 'Remember who you are';
}

const Simba = function() {
  Mufasa.call(this);
}

Simba.prototype = new Mufasa();

Simba.prototype.position	// 'king'
Simba.prototype.deliver()	// 'Remember who you are'

📎 class 키워드

하지만 ES6에서 class 문법이 생긴 이후 상속의 기능을 구현하는 방법은 조금 다르다.
우선 class 키워드를 사용하여 상위 클래스를 먼저 생성해보자.

class Mufasa {
  constructor() {
    this.position = 'king';
  }
  deliver() {
    return 'Remember who you are';
  }
}
  • 먼저 class 키워드를 이용하여 상위 클래스를 생성해준다.
  • 생성자(constructor) 키워드를 이용하여 속성을 할당해준다.
  • 메서드는 생성자를 빠져나와 별도로 선언 후 값을 할당해준다.

📎 extends & super 키워드

상위 클래스를 생성했다면 이번에는 하위 클래스를 생성해보자.
클래스를 생성하는 법은 위와 비슷하지만 또 다른 키워드 extendssuper를 사용한다.

class Simba extends Mufasa() {
  constructor() {
    super();
    this.age = 2;
    this.color = 'yellow';
  }
}
  • class 키워드를 이용하여 클래스를 생성 후 extends 키워드를 사용하여 상위 클래스의 생성자를 호출한다.
  • super 키워드를 사용하여 상위 클래스의 모든 속성들을 자동으로 상속받는다.
  • 상위 클래스와 하위 클래스의 속성값이 동일할 경우에는 자동으로 상속이 된다. ex) position
  • this를 사용하여 속성값들을 재할당 혹은 생성해준다.
profile
get, set, go!

0개의 댓글