Object Prototypes

What are object prototypes? How to use them?

Javascript Prototypes

All objects in Javascript have a prototype, which inherits properties and methods from their prototype.

We can move the functions in the object instance and put them in a prototype.

// Constructor
function Person(firstName, lastName, birthDay) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.birthDay = new Date(birthDay);
}

//getFullName
Person.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
};

// getBYear
Person.prototype.getBYear = function () {
  return this.birthDay.getFullYear();
};

// Instatiate an object
const p1 = new Person("Anna", "Wood", "3-25-1995", "green");
const p2 = new Person("Joe", "Hopkins", "10-12-1990", "blue");

console.log(p2.getFullName()); // Joe Hopkins