제공되는 Rectangle class로부터 area 메소드를 추가하고, Rectangle class를 상속받는 Square class 만들기
조건 및 제한사항
- Rectangle의 prototype에 area 메소드 추가
- 아래 조건을 만족하는 Square class 생성
- Rectangle의 하위클래스
- 생성자(constructor)만 포함하고 다른 메서드는 불포함
- Rectangle 클래스의 area 메소드를 사용하여 Square의 area를 출력
나의 풀이
- Rectangle.prototype.area = function() {} 을 이용하여 prototype 메소드 추가
- Arrow Function을 사용하지 않은 이유는 메소드로 사용할 수 없기 때문
- Rectangle.__proto__. 를 이용하여 모든 객체가 사용할 수 있도록 할당
- 단, 새로운 객체가 아니라 Rectangle.prototype에 area 메소드를 추가했기에, 두번의 선언이 불필요 하다는 생각도 듦
- 바로 __proto__에서 작업해주면 되지않았을까? 자세한건 공부하면서 다시한번 확인해보기로
- Rectangle 클래스를 할당받는 Square 클래스 생성
- Square 클래스는 하나의 인자만 받음 (후략 코드에 존재)
- 하나의 인자로 슈퍼클래스의 w, h에 할당
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
/*
* Write code that adds an 'area' method to the Rectangle class' prototype
*/
Rectangle.prototype.area = function () {
return this.w * this.h;
}
Rectangle.__proto__.area = Rectangle.prototype.area;
/*
* Create a Square class that inherits from Rectangle and implement its class constructor
*/
class Square extends Rectangle {
constructor(w) {
super(w, w);
}
}
// ...후략
결과