Front/JavaScript
JavaScript - 사용자 정의객체 연습문제
Hyeon_
2021. 12. 13. 14:45
JavaScript
사용자 정의 객체
클래스 생성 연습문제1
object7-classEx.html
프로퍼티: width, height
생성자 / getter / setter
메서드: getArea(): 넓이를 구해서 반환
출력
- getter 호출해서 가로 길이, 세로 길이 출력
- 사각형의 넓이 출력
- setter 호출해서 가로 길이, 세로 길이 변경
- 변경된 사각형의 넓이 출력
출력 내용
- 가로길이: 30, 세로 길이 10
- 사각형의 넓이: 300
- (ㅊ가로 길이를 20, 세로 길이를 30으로 변경)
- 사각형의 넓이: 600
<script type="text/javascript">
class Rectangle{
constructor(width, height){
this.width = width;
this.height = height;
}
get width(){
return this._width;
}
get height(){
return this._height;
}
set width(width){
this._width = width;
}
set height(height){
this._height = height;
}
getArea() {
return this.width * this.height;
}
}
let rectangle1 = new Rectangle(30, 10);
console.log('width: ' + rectangle1.width + ', height: ' + rectangle1.height);
console.log(rectangle1.getArea());
rectangle1.width = 20;
rectangle1.height = 30;
console.log(rectangle1.getArea());
</script>