Every time you call arrancar
a new instance of medicoInternas
is being created, so if you call curarPersonas
it will increase from 0 to 1 and when you finish running arrancar
the object medico
will be destroyed .
You must instantiate medicoInternas
out of the function arrancar
:
var medico = new MedicoInternas("Leslie", 0, "Cardiología");
function arrancar (valor) {
if (valor === 'curar') {
medico.curarPersonas();
} else {
medico.mostrarDatos();
}
}
It's better to add the instance methods in the prototype
Every function in JavaScript has a special object, called prototype
that inherits from Object
. In this special object there are all the properties and functions that every instance of that function will have.
Adding the functions in the prototype of a base function means gaining performance and good practices. When you create functions via this
you are doing that a new function is created for each instance of the base function; This is very bad as it degrades performance in complex applications. The correct thing is to add functions to the prototype:
function MedicoInternas (data) {
this.nombre = data.nombre;
this.curadas = data.personasCuradas;
this.especialidad = data.especialidadDoctor;
}
MedicoInternas.prototype.curarPersona = function () {
this.curadas++;
console.info('Persona curada');
};
MedicoInternas.prototype.mostrarDatos = function () {
console.info('Nombre:', this.nombre);
console.info('Personas curadas:', this.personasCuradas);
console.info('Especialidad:', this.especialidad);
}
This way each instance of MedicoInternas
will share the same functions . This is right and optimal and should be done like this.
Final code
function MedicoInternas (data) {
this.nombre = data.nombre;
this.curadas = data.personasCuradas;
this.especialidad = data.especialidad;
}
MedicoInternas.prototype.curarPersona = function () {
this.curadas++;
console.info('Persona curada');
};
MedicoInternas.prototype.mostrarDatos = function () {
console.info('Nombre:', this.nombre);
console.info('Personas curadas:', this.curadas);
console.info('Especialidad:', this.especialidad);
}
let medico = new MedicoInternas({
nombre: 'Leslie',
personasCuradas: 0,
especialidad: 'Cardiología'
});
arrancar('curar');
arrancar('curar');
arrancar('curar');
console.log('\n');
arrancar('datos');
function arrancar (action) {
if (action === 'curar') {
medico.curarPersona();
} else {
medico.mostrarDatos();
}
}