(function() {
function Enemy(type) {
var data = window.enemiesDataObj[type];
this.hp = data.hp;
this.attack = data.attack;
this.filterDamage = data.filterDamage;
this.type = type;
}
Enemy.prototype.damage = function(amount) {
if (this.filterDamage) {
amount = Math.round(this.filterDamage(this, amount));
}
this.hp -= amount;
}
var myEnemy = new Enemy("dragon");
document.write("HP now at " + myEnemy.hp + "<br>");
myEnemy.damage(5);
document.write("HP now at " + myEnemy.hp + "<br>");
}());
<script id="enemies" type="application/javascript">
window.enemiesDataObj = {
"bat": {
"hp": 10,
"attack": 1
},
"wolf": {
"hp": 50,
"attack": 4
},
"dragon": {
"hp": 1000,
"attack": 90,
"filterDamage": function(self, amount) {
return amount / 2;
}
}
}
</script>