JavaScript Object Constructors

A constructor is a function that creates an instance of a class which is typically called an “object”. In JavaScript, a constructor gets called when you declare an object using the new keyword.

The purpose of a constructor is to create an object and set values if there are any object properties present. It’s a neat way to create an object because you do not need to explicitly state what to return as the constructor function, by default, returns the object that gets created within it.

Example -

What happens when a constructor gets called?

In JavaScript, here’s what happens when a constructor is invoked:

  • A new empty object is created

  • this keyword starts referring to that newly created object and hence it becomes the current instance object

  • The newly created object is then returned as the constructor’s returned value

Object Types (Blueprints) (Classes)

The examples from the previous chapters are limited. They only create single objects.

Sometimes we need a "blueprint" for creating many objects of the same "type".

The way to create an "object type", is to use an object constructor function.

In the example above, function Person() is an object constructor function.

Objects of the same type are created by calling the constructor function with the new keyword:

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

Example -