Constructor Function

In this article, we will learn the constructor function and its usage.

I. What is the constructor function?

A constructor function is a function to create an object.

II. How to create a constructor function?

When we create a constructor function, we should capitalize the function’s name. Then, we pass in the properties we want to set in the parameters.

We use the keyword this to set them as the object’s properties. Avoid using arrow functions when using this in a method.

function Person(name, birthDay, color) {
  this.name = name;
  this.birthDay = new Date(birthDay);
  this.color = color;
}

III. Create an object instance

Once we have an object constructor, we use the new keyword to create new objects of the same type.

const p1 = new Person("Anna", "3-25-1995", "green");
const p2 = new Person("Joe", "10-12-1990", "blue");

console.log(p1); // Person {name: "Anna", birthDay: Tue Mar 25 1995 00:00:00 GMT+0700 (Indochina Time), color: "green"}
console.log(p2.birthDay.getFullYear()); // 1990

Note: We use the new Date() constructor to turn a string into a date object. We can use several methods with a Date object. For example:

  • getFullYear()
  • getHours()
  • getMonth()
  • getTime()
  • getUTCDay()

IV. Add methods to object

We can add a function to an object.

function Person(firstName, lastName, birthDay, color) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.birthDay = new Date(birthDay);
  this.color = color;
  this.getFullName = function () {
    return `${this.firstName} ${this.lastName}`;
  };
  this.getBYear = function () {
    return this.birthDay.getFullYear();
  };
}

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

console.log(p2.getBYear()); // 1990
console.log(p1.getFullName()); // Anna Wood