Inheritance exercise in JavaScript

5

They ask us to carry out this exercise and I have some doubts about the inheritances.

My solution that I do not know if it is correct

function Animal(nombre, especie, numPatas, cola) {
this.nombre = nombre;
this.especie = especie;
this.numPatas = numPatas;
this.cola = cola;

this.getNombre = function () {
    return this.nombre;
}

this.setNombre = function (nombre) {
    this.nombre = nombre;
}

// I omit the other getters and setters

function Vaca(nombre, especie, numPatas, cola, leche) {
Animal.call(this, nombre, especie, numPatas, cola);
this.leche = leche;


Vaca.prototype.ordeñar = function (leche) {
    this.leche = this.leche - 1;
}

Vaca.prototype.getLeche = function () {
    return this.leche;
}

    Vaca.prototype.setLeche = function (leche) {
        this.leche = leche;
    }

}

Vaca.prototype = new Animal();

function Tigre(nombre, especie, numPatas, cola, numVictimas) {
Animal.call(this, nombre, especie, numPatas, cola);
this.numVictimas = numVictimas;

Tigre.prototype.getNumVictimas = function () {
    return this.numVictimas;
}

Tigre.prototype.setNumVictimas = function (numVictimas) {
    this.numVictimas = numVictimas;
}

Tigre.prototype.comerPersonas = function (numVictimas) {
    this.numVictimas = this.numVictimas + 1;
}
}

Tigre.prototype = new Animal();

I wonder if the inheritance is correct and what a difference it would make, for example with prototype

function Animal(){     
     this.nombre = nombre;
     this.especie = especie;
     this.numPatas = numPatas;
     this.tieneCola = tieneCola;
    }
    Animal.prototype.getNombre = function(){
     return this.nombre;
    }
    Animal.prototype.setNombre = function(nombre){
     this.nombre = nombre;
    }
    
asked by Felipe Jiménez Prieto 25.05.2018 в 00:54
source

2 answers

2

Felipe the purpose of the inheritance is precisely inherit the methods and properties of the father.

In the case at hand, all objects that extend from Animal will inherit their properties and methods.

Notice that the parent's constructor is called by super to assign the parent's properties, and then, in each particular object, the properties that are not in the parent are assigned.

This sample code shows more or less how a parent method can be used from the child.

It also shows some controls that must be set in the methods, as you can see in getMilk or in cazar . Things like controlling the type of data, or not asking for more liters of milk than available. Just to indicate that setter very often need special controls.

I hope it serves you.

NOTE: This is a model similar to the one we use in object-oriented languages. Javascript gives the possibility to program like this from ES2015, which does not mean that JS is therefore a POO, as MDN says:

  

The javascript classes are introduced in the ECMAScript 2015 and are   a syntactic improvement over inheritance based on prototypes of   JavaScript. The syntax of the classes does not introduce a new model of   object-oriented inheritance to JavaScript. The JavaScript classes   provide a much clearer and simpler syntax for creating objects and   deal with the inheritance.

     

Classes in MDN (there is more interesting information in the link)

There are also other ways to do it.

This is the code.

class Animal {
  constructor(nombre, especie, numPatas, cola) {
    this.nombre = nombre;
    this.especie = especie;
    this.numPatas = numPatas;
    this.cola = cola;
  }

  /*getters
   *--------------------------------------------------------
   *Ninguno de estos getters deben ir 
   *en las otras clases que extiendan de Animal
  */
  getNombre() {
    return this.nombre;
  }

  getEspecie() {
    return this.especie;
  }

  getPatas() {
    return this.numPatas;
  }

  getCola() {
    return this.cola;
  }
   /*--------------------------------------------------------*/


  /*setters
   *--------------------------------------------------------
   *Ninguno de estos setters deben ir 
   *en las otras clases que extiendan de Animal
   *NÓTESE que los setters podrían requerir controles especiales
   *según su naturaleza. Como controlar el tipo de dato recibido
   *y cambiar el estado del objeto, sumando, restando, etc.
  */
  
  setNombre(nombre) {
    this.nombre = nombre;
  }
  setEspecie(especie) {
    this.especie = especie;
  }

  setPatas(patas) {
    this.numPatas = this.numPatas + (patas);
  }

  setCola(cola) {
    this.cola = cola;
  }

}

class Vaca extends Animal {
  constructor(nombre, especie, numPatas, cola, litros) {
    super(nombre, especie, numPatas, cola);
    /*propiedad particular de Vaca*/
    this.litros = litros;
  }


  getMilk(cantidad) {
    var msgInfo = '';
    if (isNaN(cantidad) || cantidad <= 0) {
      msgInfo = 'El dato "' + cantidad + '" no es válido';
    } else {
      var intControl = this.litros - cantidad;
      if (intControl > 0) {
        msgInfo = this.nombre + ' tenía ' + this.litros + ' litros \nSe ordeñaron ' + cantidad + ' y le quedan ' + intControl;
        this.litros = intControl;
      } else {
        msgInfo = this.nombre + ' tiene ' + this.litros + ' litros y estás pidiendo ¡' + cantidad + '! \nNo es posible!';
      }
    }
    console.log(msgInfo);

  }
}

class Tigre extends Animal {
  constructor(nombre, especie, numPatas, cola, victimas, colmillos) {
    super(nombre, especie, numPatas, cola);
    /*propiedad particulares de Tigre*/
    this.victimas = victimas;
    this.colmillos = colmillos;
  }

  //getter y setter de propiedad propia de Tigre
  getColmillos() {
    return this.colmillos;
  }

  setColmillos(colmillos) {
    this.colmillos = this.colmillos + (colmillos);
  }

  cazar(cantidad) {
    var msgInfo = '';
    if (isNaN(cantidad) || cantidad <= 0) {
      msgInfo = 'El dato "' + cantidad + '" no es válido';
    } else {
      var intControl = this.victimas + cantidad;
      this.victimas = intControl;
      msgInfo = this.nombre + ' acaba de cazar una víctima.\nAhora tiene ' + intControl;
    }
    console.log(msgInfo);
  }
}


/*VACA*/
var objVaca = new Vaca('Milex', 'Mamífero', 4, true, 10);

console.log(objVaca);
objVaca.getMilk(4);

/*Probamos un setter y getter NÓTESE QUE  SON DE LA CLASE Animal*/
objVaca.setNombre('Nueva Milex');
console.log('Ahora el objeto se llama ' + objVaca.getNombre());

/*Probamos algunos controles del ordeñado*/
objVaca.getMilk(-40);
objVaca.getMilk('a');

/*TIGRE*/
var objTigre = new Tigre('TigerHunter', 'Salvaje', 4, true, 30, 8);

/*Veamos el objeto*/
console.log(objTigre);

/*BENEFICIOS DE LA HERENCIA:
 *Podemos usar métodos de la clase Animal y de la clase Tigre
 */
console.log('Me llamo: ' + objTigre.getNombre() + ' y tengo: ' + objTigre.getColmillos() + ' colmillos');

/*El método cazar acumula víctimas*/
objTigre.cazar(3);
objTigre.cazar(0);

/*Modificamos el Tigre, y lo vemos ya viejo :)*/
objTigre.setNombre('TigerHunter ya viejo');
objTigre.setColmillos(-7);
objTigre.setPatas(-1);
objTigre.setCola(false);



console.log(objTigre);
    
answered by 25.05.2018 / 05:16
source
2

ENJOY THE KINDNESS OF THE SYNTAX OF ES6

I tell you that you can do it with the syntax of ES6, which gives you the following benefits:

  • regular classes
  • constructors
  • regular setters and getters
  • inheritance
  • instantiation
  • Below I leave you an example trying to cover the aspects of your exercise with the syntax of ES6, which is native to modern JavaScript and already has compatibility in browsers

    /*clase principal*/
    class Animal
      {
        /*constructor actúa como setters*/
        constructor(nombre, especie, numero_patas, cola){
          this._nombre = nombre
          this._especie = especie
          this._numero_patas = numero_patas
          this._cola = cola
        }
      }
    
    /*clase que hereda de Animal*/
    class Vaca extends Animal
      {
        /*constructor actúa como setters*/
        constructor(nombre, especie, numero_patas, cola, leche){
          super(nombre, especie, numero_patas, cola)
          this._leche = leche
        }
        /*aquí se declaran los getters*/
        get name(){
          return this._nombre
        }
        get especie(){
          return this._especie
        }
    
        get patas(){
          return this._numero_patas
        }
    
        get cola(){
          return this._cola
        }
    
        get leche(){
          return this._leche
        }
    
        saca_leche(){
          return '${this._nombre}, ${this._especie}, ${this._numero_patas}, ${this._cola}, ${this._leche = this._leche - 1}'
        }
      }
    
    /*clase que hereda de Animal*/
    class Tigre extends Animal
      {
        /*constructor actúa como setters*/
         constructor(nombre, especie, numero_patas, cola, victimas){
          super(nombre, especie, numero_patas, cola)
          this._victimas = victimas
        }
        /*aquí se declaran los getters*/
        get name(){
          return this._nombre
        }
        get especie(){
          return this._especie
        }
    
        get patas(){
          return this._numero_patas
        }
    
        get cola(){
          return this._cola
        }
    
        get victimas(){
          return this._victimas
        }
    
        comerPersonas(){
          return 'El tigre: ${this._nombre}, es ${this._especie}, tiene ${this._numero_patas} patas, ${this._cola}, y se comió a ${this._victimas = this._victimas + 1} pobres personas'
    
        }
      }
    
    /*la instanción ocurrirá en el objeto obj*/
    obj = new Vaca("Pancha", "mamifero", 4, true, 12)
    console.log(obj.saca_leche())
    
    /*la instanción ocurrirá en el objeto obj1*/
    obj1 = new Tigre("Tigger", "mamifero", 4, true, 4)
    console.log(obj1.comerPersonas())
    

    What results in the following

      

    "Pancha, mamifero, 4, true, 11"
    "The tiger: Tigger, mammalia, has   4 legs, true, and ate 4 poor people "

        
    answered by 25.05.2018 в 02:01