I'm trying to create a class Javascript
that allows me to have a method. This method must contain a conditional because depending on whether it is a circle or a figure with sides, the formula will be different. In the method I am using some undeclared properties that will be declared in the classes, square, circle, etc...
Since I'm quite new to classes, I don't even know if I can add a conditional inside, if I can create a local variable in the method, if I have to declare it in the constructor etc...
Could you clarify my doubts a bit and how to do it?
As always, thank you very much.
class Figura{
//Aquí he declarado la clase result. Pero en realidad no sé si es necesario
constructor(posX, posY, result){
this._posX = posX;
this._posY = posY;
this.result = result;
}
get_posX(){
return this._posX;
}
set_posX(x){
this._posX = x;
}
get_posY(){
return this._posY;
}
set_posY(x){
this._posY = x;
}
//Quizá el método no tiene mucho sentido...
calcularArea(){
if(this._radio){
this._result = 2 * Math.PI * 5;
}else{
this._result = parseInt(this._lados) * parseInt(this._lado);
}
return this._result;
}
}
Here are several concepts you don't seem to be clear on:
We can say that a method is nothing more than a function associated with an object. That is, any function could be a method in Javascript. The only thing that varies is what it's called. Therefore, as in any function, you can use any type of statement that is valid in the language, with the extra of having as context (
this
) the object that owns the function. I give you an example:A good solution is that you use inheritance. I assume that a circle and a triangle are figures, but they are not alike at all, right? Therefore, you can have a Shape class, with some common data and a calculateArea() function that you can override in any of the child classes.
On the other hand, in the function that you present, you are assigning and returning a value of the class itself at the same time, that is, when calculating the value of the area you are assigning it to the property of the class directly and then you are returning said property ( I'm telling you because I don't know if you want that specific operation)
Here is a brief example of the solution I propose:
Then you would only have to create the class objects and use their functions. I don't know if the example will help you, it's too simple but it illustrates the inheritance section a bit.