Get Programming with JavaScript - Listing 10.09
Listing 10.09 - Functions to add and show exits
JS Bin
var Place = function (title) {
this.title = title;
};
var kitchen = new Place("The Kitchen");
var dungeon = new Place("The Dungeon");
var exits = {};
var addExit = function (direction, place) {
exits[direction] = place;
};
var showExits = function () {
var keys = Object.keys(exits);
keys.forEach(function (key) {
console.log(key + " goes to " + exits[key].title);
});
};
addExit("north", kitchen);
addExit("the trapdoor", dungeon);
showExits();
Further Adventures
Listing 10.09 - Functions to add and show exits - Tasks 1 & 2
- Add a couple more places.
- Use the addExit function to add exits to your new places.
var Place = function (title) {
this.title = title;
};
var kitchen = new Place("The Kitchen");
var dungeon = new Place("The Dungeon");
var library = new Place("The Library");
var garden = new Place("The Garden");
var exits = {};
var addExit = function (direction, place) {
exits[direction] = place;
};
var showExits = function () {
var keys = Object.keys(exits);
keys.forEach(function (key) {
console.log(key + " goes to " + exits[key].title);
});
};
addExit("north", kitchen);
addExit("the trapdoor", dungeon);
addExit("west", garden);
addExit("up the ladder", library);
showExits();
Listing 10.09 - Functions to add and show exits - Task 3
- Update the showExits function so it only shows the directions, not the destinations.
var Place = function (title) {
this.title = title;
};
var kitchen = new Place("The Kitchen");
var dungeon = new Place("The Dungeon");
var library = new Place("The Library");
var garden = new Place("The Garden");
var exits = {};
var addExit = function (direction, place) {
exits[direction] = place;
};
var showExits = function () {
var keys = Object.keys(exits);
keys.forEach(function (key) {
console.log(key);
});
};
addExit("north", kitchen);
addExit("the trapdoor", dungeon);
addExit("west", garden);
addExit("up the ladder", library);
showExits();
Listing 10.09 - Functions to add and show exits - Task 4
- Write a showDestination function that shows the destination when a direction is passed to it as an argument.
var Place = function (title) {
this.title = title;
};
var kitchen = new Place("The Kitchen");
var dungeon = new Place("The Dungeon");
var library = new Place("The Library");
var garden = new Place("The Garden");
var exits = {};
var addExit = function (direction, place) {
exits[direction] = place;
};
var showExits = function () {
var keys = Object.keys(exits);
keys.forEach(function (key) {
console.log(key);
});
};
var showDestination = function (direction) {
console.log(direction + " leads to " + exits[direction]);
};
addExit("north", kitchen);
addExit("the trapdoor", dungeon);
addExit("west", garden);
addExit("up the ladder", library);
showExits();