I completely understand the concept of prototype inheritance in JavaScript if the methods in the constructor are the same for all instances. But what if I want to create objects via constructors but want the methods to produce a different result for each instance?
function Player (health, power, stamina) {
this.health = health;
this.power = power;
this.stamina = stamina;
this.recovery = function () {
return this.health += 20;
}
}
var hulk = new Person ( 100,80,60 );
var superman = new Person ( 100,70,50);
My problem here is I want hulks recovery to add 20 when I call the recovery method but I want superman’s to add 40. If I add the method to the prototype instead of directly into the object I still want that method to be only for the hulk and a different one for superman. Do I create object literals for this and specify the different methods for each object? This seems long wielded if I had hundreds of characters! Or do I add another multiple methods to the Person prototype even if it’s only going to be used by one instance? What’s the best way to make superman’s recovery better than the hulks whilst still using a constructor ? Thanks all.
Pass a 4th parameter to Player
, one which indicates health regen:
function Player(health, power, stamina, healthRegen) {
this.health = health;
this.power = power;
this.stamina = stamina;
this.healthRegen = healthRegen;
this.recovery = function() {
return this.health += this.healthRegen;
}
}
var hulk = new Person(100, 80, 60, 20);
var superman = new Person(100, 70, 50, 40);
If most characters had a particular amount of health regen (say, 20), and you only wanted superman
and a couple others to have different health regen, you could use a default parameter to avoid having to write 20
so much:
function Player(health, power, stamina, healthRegen = 20) {
this.health = health;
this.power = power;
this.stamina = stamina;
this.healthRegen = healthRegen;
this.recovery = function() {
return this.health += this.healthRegen;
}
}
var hulk = new Person(100, 80, 60);
var superman = new Person(100, 70, 50, 40);
var normalPerson = new Person(50, 50 50);
Above, see how you only need to pass the 4th parameter when the desired health regen is other than 20; otherwise, it'll default to 20.