Constructor Functions

Before Classes

Example

Before ES6, "classes" were functions called with new; shared methods were put on Function.prototype:

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return "Hi, I am " + this.name;
};
const p1 = new Person("Asha");
const p2 = new Person("Vikram");
console.log(p1.greet(), p2.greet());
console.log(p1.greet === p2.greet);     // one shared method

Output

Hi, I am Asha Hi, I am Vikram
true

What new Does

  1. Creates a new empty object.
  2. Sets its prototype to Constructor.prototype.
  3. Calls the constructor with this = the new object.
  4. Returns the object (unless the constructor returns another object).