ECMA Script 6 - inheritance

박성원·2020년 11월 20일
0

ECMA6

목록 보기
9/10
post-thumbnail

ES6에서는 자바와 같이 extends 키워드로 상속을 표현한다.
부모 클래스의 멤버를 자식 클래스가 상속 받아서 사용 가능하다.

contructor와 상속

  1. 자식 클래스와 부모 클래스 양쪽 constructor를 작성하지 않아도 인스턴스가 생성된다. (default constructor 사용)

  2. 부모 클래스에만 constructor를 작성하면, 자식 클래스의 'default 생성자'가 호출되고 부모 클래스의 constructor가 호출된다.

  3. 자식 클래스에만 constructor만 작성하면 자식 클래스의 constructor가 호출되고, 반드시 부모의 constructor를 명시적으로 호출해야한다.

  4. 자식과 부모 클래스 양쪽 constructor를 작성하면 자식 constructor가 호출되지만, 반드시 부모 constructor를 명시적으로 호출해야한다.

(자바에서와 거의 비슷한 체계를 따르는 것을 알 수 있다.)

  <script type="text/javascript">
    // 상속
    class Employee {
      constructor(name, salary) {
        console.log('부모 생성자 ========');
        this.name = name;
        this.salary = salary;
      }
      setName(name) {
        this.name = name;
      }
      setSalary(salary) {
        this.salary = salary;
      }
      getName() {
        return this.name;
      }
      getSalary() {
        return this.salary;
      }
    }
    class Manager extends Employee {
      constructor(name, salary, depart) {
        console.log('자식생성자 =========');
        super(name, salary); // 부모 생성자 명시적 호출 필수
        this.depart = depart;
      }
      setDepart(depart) {
        this.depart = depart;
      }
      getDepart() {
        return this.depart;
      }
    }

    var man = new Manager();
    man.setName('홍길동');
    man.setSalary(1000);
    man.setDepart('인사');

    console.log(man.getName());
    console.log(man.getSalary());
    console.log(man.getDepart());
  </script>
profile
개발 일기장

0개의 댓글