Understanding Constructors and their types In JavaScript

A constructor method in Javascript is a method used to create and initialize objects within a class. There are two types of constructors in javascript, namely;

  • Built-in Constructor

This is called directly when an object of the class object is created. examples are array, date, and object.

var name = new Object("john");
var age =  new Object("28");
console.log("name : "+name+" & Age : "+age);
//output "Name : john & Age : 28"
  • Custom Constructor | User-defined Constructor

These are the constructor declared and defined by the programmer to be used throughout an application. example in code:

function Book(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function displayBook(book){
console.log('\'' + book.name + '\' authored by ' + book.author +         ' in the year ' + book.year + '.');
}
var book1 = new Book('Java - The Complete Reference', 'Herbert             Schildt', 2006);
var book2 = new Book('Let Us C', 'Yashavant Kanetkar', 2002);
var book3 = new Book('Data Structures', 'Seymour Lipschutz', 2005);
displayBook(book1);
displayBook(book2);
displayBook(book3);
// output 
 "'Java - The Complete Reference' authored by Herbert             Schildt in the year 2006."
"'Let Us C' authored by Yashavant Kanetkar in the year 2002."
"'Data Structures' authored by Seymour Lipschutz in the year 2005.

Point to note about constructors in javascript:

Whenever a new object is created, the New keyword returns a reference to the newly created object and that object is accessed using This keyword inside the constructor to initialize the properties of the object.

Conclusion:

Hope you now understand a bit about constructors in javascript and their types.

Open for feedback, thank you for reading this.

find me on Twitter.