DEV Community

Cover image for Object-Oriented JavaScript and Address Books
Saoud
Saoud

Posted on

Object-Oriented JavaScript and Address Books

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Finding and Deleting Contacts

Examples


Find a Contact:

AddressBook.prototype.findContact = function(id) {
  if (this.contacts[id] != undefined) {
    return this.contacts[id];
  }
  return false;
}
Enter fullscreen mode Exit fullscreen mode

Delete a Contact:

AddressBook.prototype.deleteContact = function(id) {
  if (this.contacts[id] === undefined) {
    return false;
  }
  delete this.contacts[id];
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pau1phi11ips profile image
Paul Phillips

If you're using an OO pattern. Why don't you use define the methods within a class?

Collapse
 
saoud profile image
Saoud

I hadn't learned that yet but I shall look into it!