1. Constructor Functions

Since Javascript is a functional programming language where everything is just a function, in order to have a class like (creating a blueprint for the objects to be created) functionality in javascript, constructor functions are used, lets see how constructor functions work:

function Vehicle(make, model, color) {

this.make = make,

this.model = model,

this.color = color,

this.getName = function () {

return this.make + " " + this.model;

}

}

The function above provides almost similar functionality as that of a Java class, in order to create an object of type Vehicle , we do following:

let car = new Vehicle("Toyota", "Corolla", "Black");

let car2 = new Vehicle("Honda", "Civic", "White");

This is perfect. Ain’t it? now, we can create as many objects of type Vehicle as we want by just writing one line code.

But wait, there are a few problems with this technique.

When we write new Vehicle() , what Javascript engine does under the hood is that it makes a copy of our Vehicle constructor function for each of our objects, each and every property and method is copied to the new instance of the Vehicle , that’s okay, what is the problem in this?!

The problem here is that we don’t want the member functions (methods) of our constructor function to be repeated in every object. That is redundant. Isn’t it? Another problem is that we can’t add a new property or method to an existing object like this:

car2.year = "2012"

To add this year property you will have to add it to the constructor function itself: