Get Programming with JavaScript - Listing 5.10
Listing 5.10 - Displaying a player's health via object properties
JS Bin
var player1;
var player2;
var showPlayerHealth;
showPlayerHealth = function (playerName, playerHealth) {
console.log(playerName + " has health " + playerHealth);
};
player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
health: 50
};
player2 = {
name: "Dax",
place: "The Old Library",
health: 40
};
showPlayerHealth(player1.name, player1.health);
showPlayerHealth(player2.name, player2.health);
Further Adventures
Listing 5.10 - Displaying a player's health via object properties - Task 1
- Add a new property to the player objects called healthMultiplier.
var player1;
var player2;
var showPlayerHealth;
showPlayerHealth = function (playerName, playerHealth) {
console.log(playerName + " has health " + playerHealth);
};
player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
health: 50,
healthMultiplier: 2
};
player2 = {
name: "Dax",
place: "The Old Library",
health: 40,
healthMultiplier: 0.5
};
showPlayerHealth(player1.name, player1.health);
showPlayerHealth(player2.name, player2.health);
Listing 5.10 - Displaying a player's health via object properties - Task 2
- Add a third parameter to the definition of the showPlayerHealth function called playerHealthMultiplier.
var player1;
var player2;
var showPlayerHealth;
showPlayerHealth = function (playerName, playerHealth, playerHealthMultiplier) { // Include a third parameter
console.log(playerName + " has health " + playerHealth);
};
player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
health: 50,
healthMultiplier: 2
};
player2 = {
name: "Dax",
place: "The Old Library",
health: 40,
healthMultiplier: 0.5
};
showPlayerHealth(player1.name, player1.health);
showPlayerHealth(player2.name, player2.health);
Listing 5.10 - Displaying a player's health via object properties - Tasks 3 & 4
- Update the function so that the health displayed is first multiplied by the health multiplier.
- Add the player's healthMultiplier property as a third argument to the two calls to the showPlayerHealth function.
var player1;
var player2;
var showPlayerHealth;
showPlayerHealth = function (playerName, playerHealth, playerHealthMultiplier) {
console.log(playerName + " has health " + playerHealth * playerHealthMultiplier); // Multiply
};
player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
health: 50,
healthMultiplier: 2
};
player2 = {
name: "Dax",
place: "The Old Library",
health: 40,
healthMultiplier: 0.5
};
showPlayerHealth(player1.name, player1.health, player1.healthMultiplier); // Include the extra argument
showPlayerHealth(player2.name, player2.health, player2.healthMultiplier); // to match the extra parameter