settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Rectangle (task with JS Class)

+5 votes

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

asked in JavaScript category by user ak47seo

2 Answers

+3 votes
 
Best answer

Here is my solution and Rectangle class:

class 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);

 

answered by user eiorgert
selected by user golearnweb
+1 vote

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());

 

answered by user hues
...