Inheritance in JavaScript

2

Good, we have seen a bit of object-oriented programming in javascript and have sent us to do an exercise to use inheritance. You have to calculate the volume of a cylinder in which we have to use the radius of a circle from a previous exercise. But I do not think I'm using it well because it does not show me anything.

Code js calculate volume:

function calcularVolumenCilindro()
{
    var radio = Circulo.prototype.radio = getRadio();
    var altura = prompt("Introduce altura del cilindro: ")
    var volumen = volumenCilindro(radio,altura);
    document.write("El volumen del cilindro es: "+volumen);
}

Code js volumeCylinder:

function volumenCilindro(radio,altura)
{
    return Math.PI*radio*radio*altura;
}

Am I using the correct way to call the getRadio () method of another exercise class?

    
asked by Mario Guiber 17.01.2018 в 15:45
source

1 answer

3

Answering your question.

You are not using correctly. There is a part of the code that does not make sense:

var radio = Circulo.prototype.radio = getRadio();

If getRadio is a method of class Circulo , then to call it you simply must do, assuming you have created an object of that class:

var circulo = new Circulo(...)
var radio = circulo.getRadio()

"Modern" solution

You can use the new syntax of Clase .

In this example I use getters and setters , but you can use class methods if you are more comfortable.

class Circulo {
  constructor(radio) {
    this._radio = radio
  }
  
  get radio () { return this._radio }
  set radio(radio) { this._radio = radio }
  
  get area() { return Math.PI * (this.radio**2) }
}

const circulo = new Circulo(10)

console.log(circulo.area)

class Cilindro extends Circulo {

  constructor(radio, altura) {
    super(radio)
    this._altura = altura
  }
  
  get altura() { return this._altura }
  set altura(altura) { this._altura = altura }
  
  get volumen() { return this.area * this.altura }

}

const cilindro = new Cilindro(10, 10)

console.log(cilindro.volumen)

NOTE The exponential operator ( ** ) is part of the standard from the version ES2016 (ES7).

    
answered by 17.01.2018 / 16:25
source