Vijay Thirugnanam
Learn React

Learn React

Difference between constructor and prototype in JavaScript

Vijay Thirugnanam's photo
Vijay Thirugnanam
·Aug 27, 2021·

2 min read

JavaScript has many nuances. Constructor and Prototype are difficult to understand concepts in JavaScript. So, instead of explaining everything about constructor and prototype, I will explain only the relevant parts that cause confusion.

Consider the code below:

function Car(name) {
  this.name = name;
}

Car.prototype.drive = function() {
  console.log('driving');
}

const car = new Car('Honda');
console.log(car.name);
car.drive();

It is possible to create objects out of a function by placing the new keyword in front of the function. The function that creates the object is called constructor function. In the above code, Car is the constructor function.

But what is a prototype? Every function has a prototype object attached to it. By default, it is empty. But you can add methods to it as we did in the above example. We have a drive method attached to the function prototype.

When we create objects out of a function, the object's prototype is set to the function's prototype. So, prototype object points to an object containing functions. In this case, prototype object contains the drive function. And every object constructed out of that function inherits the prototype object. This means that the prototype object sets the template or blueprint for the constructed objects.

To access an object's prototype, we have:

obj.__proto__

To access a function prototype, we have:

fn.prototype

For the above example, the following statement holds true:

car.__proto__ === Car.prototype

Also, the code const car = new Car(name) is equivalent to the following code:

const car = {};
car.__proto__ = Car.prototype;
Car.call(car, name);

Putting new in front of a function makes the function a constructor function.

When the constructor is invoked, we create a new object, set the object's prototype to the constructor's prototype and call the constructor passing in the newly created object as the context.

I hope this clarifies the difference between constructor function and prototype object. Constructor function creates an object. Whereas prototype object is a collection of functions that sets the blueprint / template for the newly created object.

 
Share this