I have this code:
class Square {
constructor(side) {
this.side = side;
}
}
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
class calcMe {
}
const square = new Square(4);
const rectangle = new Rectangle(4, 2);
const circle = new Circle(5);
console.log(calcMe.calculate(square));
console.log(calcMe.calculate(rectangle));
And I want to make a static method that can calculate the area of these shapes. How can I tell this to the static method? My attempt is:
class AreaCalculator {
static calculate(val) {
for (let key in val) {
if (key === 'side') {
return console.log(`L'area del quadrato è ${val.side * val.side}`)
} else {
if (key === 'width') {
return console.log(`L'area del rettangolo è ${val.width * val.height}`)
} else {
if (key === 'radius') {
return console.log(`L'area del cerchio è ${val.radius * val.radius * Math.PI}`)
}
}
}
}
}
}
But is obviously wrong, even if I can console log the correct results. Can anyone can point me into the right direction? How can I have access to all the shapes values to return the correct calculation?
It would be better to encapsulate the area calculation logic within the shape object itself as it is the shape itself that should know how to calculate its own area. You would then have something like circle.area(), square.area() etc
e.g.
class Square {
constructor(side) {
this.side = side;
}
area() {
return this.side * this.side;
}
}
const square = new Square(4);
const squareArea = square.area();
It is definitely easier to use instance methods to do the calculation for each type of object.
Not sure about what you want or the second part. One thing about the methods defined in the class body is that they will be assigned to the class prototype. So here is some possible solution.
class Square {
constructor(side) {
this.side = side;
}
area(){
return this.side * this.side;
}
}
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area(){
return this.width * this.height;
}
}
class Circle {
constructor(radius) {
this.radius = radius;
}
area(){
return Math.PI * this.radius * this.radius;
}
}
class calcMe {
calculate(obj) {
return obj.area()
}
}
const square = new Square(4);
const rectangle = new Rectangle(4, 2);
const circle = new Circle(5);
console.log(calcMe.prototype.calculate(square));
console.log(calcMe.prototype.calculate(rectangle));
console.log(calcMe.prototype.calculate(circle));