They ask us to carry out this exercise and I have some doubts about inheritances.
My solution that I don't know if it's 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;
}
//skip 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();
The question arises as to whether inheritance is correct and what difference would it 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;
}
TAKE ADVANTAGE OF THE BENEFITS OF ES6 SYNTAX
I tell you that you can do it with the ES6 syntax, which gives you the following benefits:
Below is an example trying to cover the aspects of your exercise with the ES6 syntax, which is native to modern JavaScript and is already supported in browsers.
Which gives me the following result
Philip the purpose of inheritance is precisely to inherit the methods and properties of the father.
In the case at hand, all objects that extend from
Animal
will inherit its properties and methods.Note that the parent's constructor is called by
super
to assign its properties, and then, in each particular object, the properties that are not in the parent are assigned.This code example shows more or less how a method of the parent 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 incazar
. Things like controlling the type of data, or not asking for more liters of milk than those available. Just to indicate thatsetter
they very often need special checks.I hope it helps you.
NOTE: This is a model similar to the one we use in object-oriented languages. Javascript gives the possibility of programming like this since ES2015, which does not mean that JS is therefore an OOP, as MDN says:
There are also other ways to do it.
This is the code.