Get Programming with JavaScript - Listing 10.10
Listing 10.10 - An exits object in the Place constructor
JS Bin
var Place = function (title, description) {
this.title = title;
this.exits = {};
this.addExit = function (direction, exit) {
this.exits[direction] = exit;
};
this.showExits = function () {
console.log("Exits from " + this.title + ":");
Object.keys(this.exits).forEach(function (key) {
console.log(key);
});
};
};
var library = new Place("The Old Library");
var kitchen = new Place("The Kitchen");
var garden = new Place("The Kitchen Garden");
kitchen.addExit("south", library);
kitchen.addExit("west", garden);
kitchen.showExits();
Further Adventures
Listing 10.10 - An exits object in the Place constructor - Tasks 1 to 3
- Add an exit from the library to the kitchen.
- Add an exit from the garden to the kitchen.
- Show the exits for the library and the garden.
var Place = function (title, description) {
this.title = title;
this.exits = {};
this.addExit = function (direction, exit) {
this.exits[direction] = exit;
};
this.showExits = function () {
console.log("Exits from " + this.title + ":");
Object.keys(this.exits).forEach(function (key) {
console.log(key);
});
};
};
var library = new Place("The Old Library");
var kitchen = new Place("The Kitchen");
var garden = new Place("The Kitchen Garden");
kitchen.addExit("south", library);
kitchen.addExit("west", garden);
library.addExit("north", kitchen);
garden.addExit("east", kitchen);
kitchen.showExits();
library.showExits();
garden.showExits();
Listing 10.10 - An exits object in the Place constructor - Task 4
- Add a couple more places and link them into the map.
var Place = function (title, description) {
this.title = title;
this.exits = {};
this.addExit = function (direction, exit) {
this.exits[direction] = exit;
};
this.showExits = function () {
console.log("Exits from " + this.title + ":");
Object.keys(this.exits).forEach(function (key) {
console.log(key);
});
};
};
var library = new Place("The Old Library");
var kitchen = new Place("The Kitchen");
var garden = new Place("The Kitchen Garden");
var dungeon = new Place("The Dungeon");
var shed = new Place("The Garden Shed");
kitchen.addExit("south", library);
kitchen.addExit("west", garden);
library.addExit("north", kitchen);
library.addExit("down", dungeon);
garden.addExit("east", kitchen);
garden.addExit("north", shed);
dungeon.addExit("up", library);
shed.addExit("south", garden);
kitchen.showExits();
library.showExits();
garden.showExits();
dungeon.showExits();
shed.showExits();