This may be a non-problem, but I have a feeling learning about proper practices will help me learn proper javascript techniques! I'm just starting with using objects and attaching functions to them. Here is the current setup I am using for a little combat simulator:
var standardAttack = function(attacker,target){
if(!target.alive) return false;
var damage = r(attacker.damage)+1-target.def;
if(damage>0) {
target.hp -= damage;
sendMessage(attacker.name+" hits "+target.name+" for "+damage.toString());
if(target.hp<1){
sendMessage(target.name+[" is torn asunder!"," has it's head ripped off!"," is trampled into the dirt!"," is sliced in half!"," is smashed to pieces!"," falls to the ground, gurgling!"," flails and dies on the ground!"].sample()+" by "+attacker.name);
target.alive = false;
}
} else {
sendMessage(attacker.name+" hits "+target.name+" but no damage is dealt");
}
}
While the Creature object looks like this:
class Creature {
constructor() {
this.name = getName();
this.alive = true;
this.hp = 6;
this.def = 0;
this.damage = 6;
this.attack = standardAttack;
}
}
There are various different types of attacks in a similar format to standardAttack, and when needed, creature.attack is changed.
From this, attacks are started with:
creature1.attack(creature1,creature2);
or something along those lines. Looking at this, I feel like there is a more efficient way to access creature1.name and creature1.damage than passing itself into it's own function, a needless duplication. In addition, I don't think I am wrong in saying that it just looks bad! I feel that a more suitable format would be:
creature1.attack(creature2);
But currently, the standardAttack function is unable to find the damage or name values of the creature1 object. My question is this - is there any way to access the details of creature1 without passing the whole object into it's own function?
Please let me know if there are any changes I need to make to the question as well.