Javscript 상속

BooKi·2022년 3월 7일
0

Javascript

목록 보기
45/46
post-thumbnail

⭐Javscript 상속

📕상속

상속을 알아보기 위해선 기본적으로 클래스가 존재해야 하기 때문에

Rectangle 클래스를 먼저 만들어 보겠다

<script>
  class Rectangle {
    constructor(width, height){
      this.width = width
      this.height = height
    }
    getArea (){
      return this.width * this.height
    }
    getPerimeter () {
      return 2 * ( this.width + this.height )
    }
  }

  const rect = new Rectangle(2, 5)
  console.log(rect.getArea())
  console.log(rect.getPerimeter())

</script>

이렇게 넓이와 변의 합을 구해주는 클래스를 만들었다

근데 직사각형 말고 정사각형의 넓이와 변의 합을 구해주는 클래스가 필요하다고 하자

똑같이 새로운 클래스를 다시 만들어도 된다

그러나 비슷한 클래스를 구현할 때마다 따로 만드는 것은 유지보수를 어렵게 한다

이렇게 비슷한 기능을 가진 클래스는 뒤에 extends를 붙이고

상속받을 클래스의 이름을 쓰면 된다

<script>
  class Rectangle {
    constructor(width, height){
      this.width = width
      this.height = height
    }
    getArea (){
      return this.width * this.height
    }
    getPerimeter () {
      return 2 * ( this.width + this.height )
    }
  }
  class Square extends Rectangle { }

  const rect = new Rectangle(2, 5)
  console.log(rect.getArea()) -> 10
  console.log(rect.getPerimeter()) -> 14

  const square = new Square(4, 4)
  console.log(square.getArea()) -> 16
  console.log(square.getPerimeter()) -> 16

</script>

이렇게 하면 따로 클래스를 만들지 않고 슈퍼클래스의 메소드와 변수를

그대로 사용할 수 있다

📗용어

용어를 설명하면 코드에서 Rectangle 처럼 주는 클래스는

부모 클래스 or 슈퍼 클래스 라고 한다

코드에서 Square 처럼 받는 클래스를

자식 클래스 or 서브 클래스 라고 한다

지금 코드를 살펴보면 정사각형은 한 변의 길이만 있어도 되는데

두 변의 길이를 넣을 필요는 없다

그래서 전체를 상속받지만 일부를 수정할 수 있다

덮어쓰기를 한다고 생각하면 편하다

그리고 서브클래스가 상속을 받았다라는것을 나타내기 위해서

생성자를 추가적으로 작성할 때는 맨위에 super()를 작성해야한다

super()는 부모의 생성자를 의미한다

<script>
  class Rectangle {
    constructor(width, height){
      this.width = width
      this.height = height
    }
    getArea (){
      return this.width * this.height
    }
    getPerimeter () {
      return 2 * ( this.width + this.height )
    }
  }
  class Square extends Rectangle {
    constructor (width) {
      super()
      this.width = width
      this.height = width
    }
  }

  const rect = new Rectangle(2, 5)
  console.log(rect.getArea())
  console.log(rect.getPerimeter())

  const square = new Square(4)
  console.log(square.getArea())
  console.log(square.getPerimeter())

</script>

이렇게 하거나 굳이 width, height를 쓰지않고 super(width, width) 이렇게

작성해도 된다

  class Square extends Rectangle {
    constructor (width) {
      super()
      this.width = width
      this.height = width
    }
  }
  -------------------------------- 위와 아래가 같다
  class Square extends Rectangle {
    constructor (width) {
      super(width, width)
    }
  }

profile
성장을 보여주는 기록

0개의 댓글