본문으로 바로가기

extends

category 웹 개념/javascript 2022. 4. 20. 20:21

extends

extends를 사용하면 프로토타입과 같이 class를 확장시켜 사용할 수 있다.

extends를 클래스 상속이라 부른다.

 

 

Case1

class Animal {
  constructor(name) {
    this.speed = 0;
    this.name = name;
  }
  run(speed) {
    this.speed = speed;
    console.log(`${this.name} 는 속도 ${this.speed}로 달립니다.`);
  }
  stop() {
    this.speed = 0;
    consoloe.log(`${this.name} 가 멈췄습니다.`);
  }
}

let animal = new Animal("동물");

Animal 클래스를 만들고 클래스 안에 construction 함수를 만든다.

construction은 기본으로 객체를 설정하는 메서드이므로 다른 함수에 값을 전달해준다.

그래서 우리가 필요한 함수메서드를 그때마다 호출하여 animal.stop() 처럼 사용할 수 있다.

class Rabbit extends Animal {
  hide() {
    alert(`${this.name} 이/가 숨었습니다!`);
  }
}

let rabbit = new Rabbit("토끼");

rabbit.run(5); // 토끼 는 속도 5로 달립니다.
rabbit.hide(); // 토끼 가 숨었습니다!

위 처럼 Rabbit extends Animal를 사용하게 되면 "기존에 만든 Animal 클래스에 rabbit 클래스를 연장한다"라고 생각할 수 있다.

객체나 함수에서 사용하던 프로토타입과 같이 클래스 상속이라 생각하면 된다.

Animal에 hide()를 이어붙여 Rabbit이라는 클래스를 만들었다.

생성자 함수로 만들어 rabbit변수에 저장하고 원하는 값을 매서드로 호출하여 출력할 수 있다.

 

 

출처:https://velog.io/@ldaehi0205/Javascriptclass-extends

'웹 개념 > javascript' 카테고리의 다른 글

super  (0) 2022.04.20
arguments 객체  (0) 2022.04.20
constructor  (0) 2022.04.20
Object.create  (0) 2022.04.20
apply,call,bind  (0) 2022.04.20