[JavaScript] 상속 extends, super()

Bloomin·2023년 2월 14일

JavaScript

목록 보기
1/3

클래스 상속

클래스 상속을 사용하면, 기존에 존재하는 기능을 확장, 수정(extends)하여 다른 기능을 추가할 수 있다.

extends, super

Human이라는 클래스에는 생성자와 printGender라는 Method가 있다.

class Human{
  constructor() {
    this.gender = 'female';
  }
  
  printGender(){
    console.log(this.gender);
  }
}

Human을 상속하여 만든 Person이라는 클래스에는 생성자와 printMyName이라는 Method가 있다.

class Person extends Human{
  constructor() {
    super();
    this.name = 'MJ';
  }
  
  printMyName(){
    console.log(this.name);
  }
}

Person은 Human을 상속하므로, Human에 정의된 printMyGender라는 Method도 호출하여 사용할 수 있다.

const person = new Person();
person.printMyName();
person.printGender();

하지만, extends 키워드만 넣는다고 Human의 속성을 상속할 수 있는 것은 아니다.
생성자가 Person을 생성할 때, 상위클래스인 Human의 생성자를 먼저 초기화시킬 수 있도록 무조건 super()를 호출해야 한다.

상속의 활용

React에서 컴포넌트를 만들 때 상속을 사용함

profile
기록하는 습관

0개의 댓글