3
06/11/2024 6:21 오후
주제 스타터
Write a JS class for a rectangle object. It needs to have a width (Number), height (Number) and color (String) properties, which are set from the constructor and a calcArea() method, that calculates and returns the rectangle’s area.
입력:
The constructor function will receive valid parameters.
출력:
The calcArea() method should return a number.
Submit the class definition as is, without wrapping it in any function.
예시:
Sample Input:
let rect = new Rectangle(4, 5, 'red');
console.log(rect.width);
console.log(rect.height);
console.log(rect.color);
console.log(rect.calcArea());
출력:
4
5
Red
20
1개 답글
2
06/11/2024 6:22 오후
Here is my solution and Rectangle class:
lass Rectangle {
constructor(width, height, color) {
/* this.width = width;
this.height = height;
this.color = color;*/
[this.width,this.height,this.color]=[width, height, color];
}
calcArea() {
return this.width * this.height;
}
}
let rect = new Rectangle(4, 5, 'red');
//console.log(rect.width);
//console.log(rect.height);
//console.log(rect.color);
console.log(rect.calcArea());
console.log(rect);
Another solution with old JS legacy code used before Classes implementation in JavaScript:
function Rectangle(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
Rectangle.prototype.calcArea = function () {
return this.width * this.height;
};
}
let rect = new Rectangle(3, 4, "red");
console.log(rect);
console.log(rect.height);
console.log(rect.width);
console.log(rect.color);
console.log(rect.calcArea());
