DEV Community

loading...
Cover image for Object-Oriented JavaScript and Address Books

Object-Oriented JavaScript and Address Books

saoud profile image Saoud ・1 min read

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

Discussion (2)

pic
Editor guide
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 Author

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