javascript class 상속하기

최석훈·2021년 2월 24일
0

class 상속하는 법을 배워보자.

class Shape{
  constructor(width, height, color){
    this.width = width;
    this.height = height;
    this.color = color;
  }
  
  draw(){
    console.log(`drawing ${this.color} color!);
  }
  
  getArea(){
    return (this.width * this.height);
  }
}

class는 이렇게 선언할 수있다. constructor 메서드는 class내에서
객체를 선언하고 초기화하기 위한 특별한 메서드이다.
그리고 draw, getArea처럼 우리가 직접 메서드를 만들 수도 있다.

class Rectangle extends Shape{
  draw(){
   super.draw();
   console.log('🔺');
  }
}

class Triangle extends Shape{
  getArea(){
    return (this.width * this.height /2)
  }
}

extends를 사용하여 Shape를 상속받는 Rextangle과 Triangle class를
선언하였다. Rectangle와 Triangle은 Shape를 상속받았기 때문에 draw()와 getArea() 메소드를 사용할 수 있다(물론 constructor도). 하지만 상속받는 메서드를 바꾸고 싶다면 Rectangle처럼 draw()의 내용을 변경해주면 된다. 만약 상속받은 draw()내용을 사용하고 싶다면 super를 이용해서 사용할 수 있다.

const rectangle = new Rectangle(20, 20, blue);
rectangle.draw()
console.log(rectangle.getArea())

const triangle = new Triangle(20, 20, red);
triangle.draw()
console.log(triangle.getArea())

위 코드의 결과는 이와같다.

drawing blue color!
🔺
400

drawing red color!
200

profile
하루를 열심히

0개의 댓글