I wrote this snippet of code, trying to create an impromptu fighting game. It uses the old style function keyword, therefore when I want to use a helper function isAlive I'm forced to do a very ugly 'this' binding.
I'm trying to grasp how 'this' behaves differently with arrow functions but when I change the first line to ES6 syntax and drop the binding it always returns false.
let isAlive = () => this.health > 0;
What am I doing wrong? I'm pretty sure the syntax itself is OK.
let isAlive = function () { return this.health > 0};
let getFighter = function (color, strength) {
return {
color: color,
health: 100,
strength: typeof strength !== 'undefined' ? strength : 1,
attack: function (what) {
hit_points = Math.floor(Math.random() * 10 * this.strength);
document.writeln(this.color + ' fighter attacks ' + what.color + ' trying to deal ' + hit_points + ' damage.');
what.get_hurt(hit_points);
},
get_hurt: function (hit_points) {
if ( !isAlive.bind(this)() ) {
document.writeln(this.color + ' fighter already dead!');
document.writeln();
return;
}
this.health = this.health - hit_points;
document.writeln(this.color + ' received ' + hit_points + ' damage and has ' + this.health + ' HP left.');
if ( !isAlive.bind(this)() ) {
document.writeln(this.color + ' fighter died!');
}
document.writeln();
}
};
};
blue = getFighter('Blue', 3);
red = getFighter('Red');
console.log(red);
console.log(blue);
while (isAlive.bind(blue)()) {
red.attack(blue);
}
red.attack(blue)