(function() { var enemiesDataStr = document.getElementById("enemies").innerHTML; var enemiesDataObj = JSON.parse(enemiesDataStr); function Enemy(type) { var data = enemiesDataObj[type]; this.hp = data.hp; this.attack = data.attack; this.type = type; } Enemy.prototype.damage = function(amount) { // Dragon specific code! if (this.type === "dragon") { amount = Math.round(amount / 2); } 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="json"> { "bat": { "hp": 10, "attack": 1 }, "wolf": { "hp": 50, "attack": 4 }, "dragon": { "hp": 1000, "attack": 90 } } </script>