Address Book: Objects Within Objects
Examples
Add contacts to an AddressBook with its constructor and prototype methods:
scripts.js
// Business Logic for AddressBook --------- function AddressBook() { this.contacts = {}; } AddressBook.prototype.addContact = function(contact) { this.contacts[contact.firstName] = contact; } // Business Logic for Contacts --------- function Contact(firstName, lastName, phoneNumber) { this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; } Contact.prototype.fullName = function() { return this.firstName + " " + this.lastName; }
Unique IDs
Example
Here's how scripts.js will look by the end of the lesson:
scripts.js
// Business Logic for AddressBook --------- function AddressBook() { this.contacts = {}; } AddressBook.prototype.addContact = function(contact) { contact.id = this.assignId(); this.contacts[contact.id] = contact; } AddressBook.prototype.assignId = function() { this.currentId += 1; return this.currentId; } // Business Logic for Contacts --------- function Contact(firstName, lastName, phoneNumber) { this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; } Contact.prototype.fullName = function() { return this.firstName + " " + this.lastName; }
Finding and Deleting Contacts
Examples
Find a Contact:
AddressBook.prototype.findContact = function(id) { if (this.contacts[id] != undefined) { return this.contacts[id]; } return false; }
Delete a Contact:
AddressBook.prototype.deleteContact = function(id) { if (this.contacts[id] === undefined) { return false; } delete this.contacts[id]; return true; }