Posted by : at

Category : programming   javascript

Unlike many other languages, Javascript does not support Classes, but it has constructors to bring similar functionality to Javascript.In this tutorial, we will explore constructors in detail and see how Javascript utilizes them to make objects.

So What is a Constructor ?

It’s an ordinary function that is used with the new operator to produce a specialized type of object.

var blue = new Color(255, 0, 0);
// Here Color is a constructor

In this example, blue is a new “Color” object. But how does that work?

function Color(r, g, b){
    this.r = r;
    this.g = g;
    this.b = b;

var blue = new Color(255, 0, 0);

As you can see, the Color constructor is merely taking the arguments given to it and attaching them to the this object. That’s because when the constructor is invoked by new, the constructor’s this is set to the object that new will return.

So, actually behind the scenes, something like this will happen:

var blue = {
    r: 255,
    g: 0,
    b: 0

So Why do we use Constuctor ?

  1. Using a constructor means that all these objects will be created with same basic structure.

  2. Using a constructor means that the object is explicitly marked as an instance of Color.

var red = new Color(255, 0, 0);

var blue = { r: 255, g: 0, b: 0};

// Outputs : true
console.log(red instanceof Color);

// Outputs: false
console.log(blue instanceof Color);
  1. Using a constructor means that we can easily assign specialize methods to the constructor’s prototype, and they will instantly be available to all the objects created by the constructor.
function Color(r, g, b){
    this.r = r;
    this.g = g;
    this.b = b;

Color.prototype.getAverage = function(){
    var total = this.r + this.g + this.b;
    var avg = total / 3;
    return parseInt(avg, 10);

var blue = new Color(255, 0, 0);
var white = new Color(255, 255, 255);

// Outputs : 85

// Outputs : 255

When do we use Constructor ?

A Constructor is useful when you want to create multiple similar objects with the same properties and methods. It’s a convention to capitalize the name of constructors to distinguish them from regular functions

So if i want to create many Games which has similar properties like Game Title, Genre, Year of Release etc. I would create objects like this in Javascript

function Game(title, genre, release_year) {
    // defining the game properties
    this.title = title;
    this.genre = genre;
    this.release_year = release_year;

var myGame = new Game("Devil May Cry", "Action", 2005);

This will create a new Game Object :

    "title": "Devil May Cry",
    "genre": "Action",
    "release_year": 2005