3
06/11/2024 6:21 pm
Topic starter
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.
Input:
The constructor function will receive valid parameters.
Output:
The calcArea() method should return a number.
Submit the class definition as is, without wrapping it in any function.
Examples:
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());
Output:
4
5
Red
20
1 Answer
2
06/11/2024 6:22 pm
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());