JavaScript ES6 문법 - extends

박재휘·2024년 3월 2일

JavaScript

목록 보기
10/19
post-thumbnail

extends

class를 상속해서 다른 class를 만들 때 사용한다.

class직접 하드코딩해서 만들어도 되지만 class의 내용이 너무 많은 경우 코드가 길어지기 때문에 extends문법을 이용하면 기존 class내용을 상속해여 또 하나의 class를 만들 수 있게 도와준다.

class Father {
  constructor(name) {
    this.= "Hong";
    this.이름 = name;
  }
}

class Son extends Father {
  constructor(name) { // 부모 클래스의 파라미터도 그대로 가져와야한다.
    super(name); // Father클래스의 this.성, this.이름을 의미한다.
    this.age = 20;
  }
}

var son = new Son('Gil Dong');

console.log(son);
  • super()extends로 상속중인 부모 클래스의constructor()를 의미한다. super()를 쓰지 않으면 에러가 난다.

  • extends로 상속중인 부모 클래스의 파라미터가 있다면 그대로 명시해주어야 한다.

super

super는 위치에 따라서 두가지 의미를 가진다.

class Father {
  constructor(name) {
    this.= "Hong";
    this.이름 = name;
  }
  sayHi(){
    console.log('Hello I am Father')
  }
}

class Son extends Father {
  constructor(name) {
    super(name);
    this.age = 20;
    // 여기(constructor)에서 super()은 부모 클래스의 constructor
  }
  // 여기(prototype함수)에서 super()은 부모 클래스의 prototype
}
    1. constructor안에서 사용하면 처음 예시코드처럼 부모클래스의 constructor()안에 들어있던 속성과 값들을 의미한다.
    1. prototype 함수 안에서 사용하면 부모 클래스의 prototype을 의미한다.
profile
차곡차곡 열심히

0개의 댓글