728x90
Polymorphism (다형성)
- 필요한 메서드를 재정의 해서 사용할 수 있다 (오버라이딩)
- 오버라이딩 한 상태에서 부모 class의 메서드를 사용하고 싶으면 super 키워드를 사용하면 된다
// 부모 class
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color of`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw(); // 오버라이딩 해도 부모 class 메소드 호출 쌉가능
console.log(`📐`);
}
// 오버라이딩(다형성)
getArea() {
return (this.width * this.height) / 2;
}
}
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());
728x90
'기술 면접 정리 > 자바스크립트' 카테고리의 다른 글
자바스크립트 엔진 (0) | 2022.04.15 |
---|---|
preventDefault(); 와 stopPropagation(); 차이 (0) | 2022.04.12 |
접근 제어자 (0) | 2022.04.03 |
static (0) | 2022.04.02 |
JavaScript (0) | 2021.11.13 |