Constructor Function

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

I. What is constructor function?

Constructor function is the function to create an object.

II. How to create constructor function?

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

We use the keyword this to set them as the properties of the object. 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 new Date() constructor to turn string into 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 function in 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