ES6 Classes, Constructor Functions and Prototypal Inheritance in JavaScript

Rohit kumarRohit kumar
8 min read

What are classes in ECMAScript 6?

“In JavaScript classes are the blueprint of creating Object”. This we have heard over every blog, article and documentation, but what does this actually mean. Let’s understand by a small real life example, Suppose you are a builder, and you are building a housing colony for the people. And you want to give the same type of houses to everyone. Now, you have two options, You can start building the houses immediately, the other option is that you can start planning the structure of the house and then, start building that. You might like the second approach, because in first approach we don’t have planning and we started building the house, it may lead to problems, that some houses will be small, some houses will be big and so on. But in the second approach as we have planned, means first created a blueprint of the house that how it should be, what should be the design, how much floor is it and so on. So with one blueprint we can create houses in a confined land area. Similar is the case of classes in JavaScript, classes is the blueprint of the houses to build and whereas actual houses are the objects, as you can build as many houses as you can from the blueprint, same is the case in the object, you can create as many object from the blueprint.

class House{
    constructor(type, floor){
        this.type = type
        this.floor = floor
    }
    houseType(){
        console.log(`This is a ${this.type} house with ${this.floor}`)
    }
}
const house1 = new House("duplex", "2")
house1.houseType(); // This is a duplex house with 2

What happened, upto class I was okay, now suddenly these many keywords came, what are these “constructor”, “new” and “this” and how all of these are working.

Let’s understand them one by one…

What is a constructor keyword?

A constructor keyword is an special method in Javascript classes, it is a special type ofmethod which help to create new objects and also initialize those objects. It's the first method that is automatically called whenever a new object (an instance) of that class is created. It defines the properties (data) and methods(behaviours) that each instance of the object will have.

What is “this” keyword?

The “this” keyword in Javascript is incredibly dynamic. In the Javascript classes the this keyword is automatically bound to the newly created empty object. Without this, your constructor wouldn’t know which object to attach the data and behaviours to.

What is “new” keyword?

Javascript classes are called with new keyword. New keyword is responsible for creation of the empty objects and point the this keyword towards the newly created object. It's the operator that transforms a regular function call into a powerful object-creation mechanism. Without new, a constructor never know which object to initiate, leading to unexpected results.

Let’s understand the previous Example…

const house1 = new House("duplex", "2);
house1.houseType(); // This is a duplex house with 2
  • new keyword: Created a new empty object house1 and point the this keyword to newly created empty object.

  • constructor keyword: initializing the values to the properties and methods.

 this.type = type
 this.floor = floor
  • this keyword: points towards the empty objects, and helps to get initalized under a certain property name, like house1 will have

    • type: duplex

    • floor: 2

Ok, Now I understood a little bit about ES6 Classes, but as the topic is mentioned, What is Constructor function?

Let’s disscuss…

What is Constructor Functions in JavaScript?

A constructor function in JavaScript is a traditional function used as a blueprint to create and initialize new objects. Its primary purpose is to define the initial state (properties and methods) that each new instance of an object will possess. Conventionally, these functions are named with a capital letter and are intended to be invoked using the new keyword to ensure this correctly references the new object being created.

Is there any similarites between ES6 Classes and Constructor Functions?

In modern JavaScript, ES6 classesare modern alternative to construct function syntax. The constructor keyword within an ES6 class serves an identical purpose to a constructor function: it's a special method automatically called when a new instance of the class is created with new. Both mechanisms essentially define how an object's initial properties are set up and how this is bound to the new instance.

“Syntactic sugar”: behind the scenes, ES6 classes work exactly like constructor functions.

// Constructor Function for House
function House(type, floor) {
  this.type = type;   
  this.floor = floor;
}

House.prototype.houseType = function() {
  console.log(`This is a ${this.type} house with ${this.floor}`);
};

const house1 = new House("duplex", "2");

house1.houseType();

Let’s go through this step-by-step.

Step 1: Defining the Constructor Function

function House(type, floor)

Here, House is the name of the constructor function, and some properties are added inside this function like type and floor. Now, when a new object is created we can pass these properties to them.

Step 2: The this keyword

this.type = type;   
this.floor = floor;

The this keyword will help us to point towards the new instance objects which will be created using House constructor function. For example if we write this.floor = floor we are telling that, please set the floor property to the new object created using House constructor function.

Step 3: Adding method to proptotype

House.prototype.houseType = function() {
  console.log(`This is a ${this.type} house with ${this.floor}`);
};

The above line of code ensures that houseType method is created. Now, the houseType method will be created once in the memory, because every object have their prototype (shared location where we can keep all their methods). if we don’t use the prototype and instead of that we will write the following code then,

this.houseType = function() {
    console.log(`This is a ${this.type} house with ${this.floor}`);
  };

if we created 100 instance object using House constructor function, then on all the object instances this method will be available, thanks to this keyword, which will unnessary increase the memory of the object, which is redundant and wastes memory.

Step 4: Creating an Instance with new keyword

const house1 = new House("duplex", "2");

When we call new House(“duplex”, “2”), a new Object is created and the following activites happens behind the seen:

  1. When a new keyword is called, it will imediately creates an empty object.

  2. constructor function is called and this keyword is pointed towards the empty object that is created by new keyword.

  3. The properties and methods are added to this.

  4. Empty object {} is linked to the prototype.

  5. Finally, it returns this, which is the newly created object.

Now, when you call house1.houseType() , you get the output. Thus, the constructor function.

Okay, Now I understood a little, about ES6 Classes and Constructor Functions, but what are Prototypal Inheritance?

What is Prototypal Inheritance?

The prototype contains methods(behaviours) that are acessible to all objects linked to that prototype.

At its core, prototypal inheritance means that every JavaScript object has a private property that holds a link to another object called its prototype. When you try to access a property or method on an object, and that property/method isn't found directly on the object itself, JavaScript automatically looks it up on the object's prototype. If it's still not found there, it continues up the prototype chain (the prototype's prototype, and so on) until it either finds the property/method or reaches the end of the chain (null). This dynamic lookup mechanism is what allows for powerful code reusability.

The above image visually clarifies the following:

  1. Constructor Function & Prototype: The House function acts as a blueprint, and its prototype object (containing houseType) is a shared space for methods.

  2. new Keyword's Role: When new House() is called, it creates house1, links it to House.prototype via __proto__, and binds this for property assignment.

  3. Prototypal Chain: If houseType isn't on house1 directly, JavaScript looks up the "Prototypal Chain" to House.prototype to find it.

  4. Inheritance/Delegation: This __proto__ link signifies prototypal inheritance, where house1 delegates method calls to its prototype.

  5. Efficient Method Sharing: Methods on the prototype are created once, saving memory as all instances share the same function definition.

Conclusion

Here are some conclusions summarizing what we've discussed about constructor functions, ES6 classes, and prototypal inheritance:

  1. Constructor Functions as Blueprints: We began with constructor functions, identifying them as traditional JavaScript functions (capitalized by convention) used with the new keyword to create and initialize new object instances, setting their initial properties and behaviors.

  2. The this Keyword's Crucial Role: Inside a constructor function or an ES6 class's constructor, the this keyword dynamically binds to the newly created object instance, enabling you to attach unique properties and methods to that specific object.

  3. The new Keyword's Power: The new operator is essential; it creates a new empty object, binds this to it within the constructor, executes the constructor's code, and implicitly returns the fully initialized object. Without new, constructors behave as regular functions.

  4. ES6 Classes: Modern Syntax: ES6 classes provide a cleaner, more structured syntax for object-oriented programming in JavaScript, acting as "syntactic sugar" over the underlying prototypal inheritance model for defining blueprints.

  5. constructor Method in Classes: Within an ES6 class, the constructor is a special method automatically invoked when a new instance is created, serving the same initialization purpose as a constructor function, handling argument reception and property assignment to this.

  6. Prototypal Inheritance: The Core Mechanism: JavaScript's unique object model relies on prototypal inheritance, where objects inherit properties and methods by linking to a prototype object. When a property isn't found directly on an object, the JavaScript engine looks up the prototype chain.

  7. Shared Methods & Efficiency: Both constructor functions (via Function.prototype) and ES6 classes (automatically) place shared methods on the prototype. This ensures methods are created only once in memory and are efficiently reused by all instances of an object, leveraging the prototype chain for lookup.

0
Subscribe to my newsletter

Read articles from Rohit kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohit kumar
Rohit kumar