Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 33

ES6 Classes vs. Prototype Inheritance

This lesson is built with resources from youtube.com, prateeksurana.me and 1 more site.

Hello! Welcome to the first lesson of our fifth module, "Advanced OOP: Classes and Encapsulation."

In the previous module, we concluded by exploring a sophisticated pattern using Proxies and a WeakMap to create private-like properties for objects. This was a powerful demonstration of metaprogramming, but it's also quite complex for what should be a common task. This naturally leads us to the question: doesn't JavaScript have a more direct way to handle this?

The answer is yes. This module dives into JavaScript's modern Object-Oriented Programming features, which provide clearer and more idiomatic solutions for encapsulation and inheritance. Today, our learning outcome is to contrast ES6 class syntax with the traditional prototype-based inheritance chain. We'll deconstruct what "syntactic sugar" really means in this context and build a solid foundation for the rest of the module.

The Problem: Code Duplication and Maintenance

Before we dive into syntax, let's briefly revisit why inheritance is a useful concept. Its primary goal is to enable code reuse and create logical hierarchies.

Inheritance in JavaScript - Prototypal Inheritance tutorial

This short video from the ColorCode channel sets the stage perfectly by explaining the fundamental problems that inheritance patterns aim to solve: code duplication and the difficulty of updating shared logic across multiple objects.

Watch this section to get a clear, practical understanding of why these patterns are necessary in the first place.


The Traditional Approach: Constructor Functions and Prototypes

Prior to ES6 (2015), JavaScript did not have a class keyword. The primary pattern for creating "classes" and enabling inheritance was through constructor functions and direct manipulation of the prototype chain.

A constructor function is a regular function that is invoked with the new keyword. By convention, its name is capitalized. The new keyword triggers four key actions:

  1. A new, empty object is created.
  2. This new object is linked to the constructor function's prototype object.
  3. The constructor function is called with this bound to the new object.
  4. The new object (this) is returned implicitly (unless the function explicitly returns another object).

Methods intended to be shared by all instances are not defined inside the constructor. Doing so would create a new copy of the function for every single object, which is inefficient. Instead, they are added to the constructor function's prototype property.

// The "old way" using a constructor function
function Person(name, age) {
  // Properties defined on 'this' are unique to each instance
  this.name = name;
  this.age = age;
}

// Methods defined on the prototype are shared by all instances
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

const alice = new Person('Alice', 30);
const bob = new Person('Bob', 25);

alice.greet(); // "Hello, my name is Alice."
bob.greet();   // "Hello, my name is Bob."

console.log(alice.greet === bob.greet); // true - both instances share the *same* function object.

When you call alice.greet(), JavaScript first checks if the alice object has its own greet property. It doesn't. So, it follows an internal link (historically accessible via __proto__, but more correctly accessed with Object.getPrototypeOf()) to its prototype, which is Person.prototype. It finds the greet method there and executes it. This lookup process is the prototype chain.

How JavaScript Classes work under the hood

The article 'How JavaScript Classes work under the hood' by Prateek Surana provides a fantastic explanation of this traditional mechanism. It details the role of constructor functions and the 'new' keyword.

Read the section titled 'The prototype for creating prototypes'. This will solidify your understanding of how constructor functions and their prototype property work together to create reusable objects.


The Modern Approach: ES6 class Syntax

Recognizing the verbosity and often confusing nature of the prototype pattern, ES6 introduced the class keyword. It's crucial to understand that this did not introduce a new object-oriented inheritance model to JavaScript. It is purely syntactic sugar over the existing prototype-based mechanism.

Let's refactor our Person example using the class syntax:

// The "new way" using ES6 class syntax
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const alice = new Person('Alice', 30);
const bob = new Person('Bob', 25);

alice.greet();
console.log(alice.greet === bob.greet); // true - still shared via the prototype!

This code is functionally identical to the constructor function version.

  • The constructor method is the constructor function.
  • The greet method is automatically placed on Person.prototype.

The class syntax provides a much cleaner, more declarative, and less error-prone way to achieve the same result.

ES6 Class vs. Prototype-based Inheritance
This image provides a clear side-by-side comparison, contrasting the older constructor function pattern with the modern, more readable ES6 `class` syntax for defining a blueprint for objects.

The Contrast: Implementing Inheritance

The difference between the two approaches becomes stark when we implement inheritance.

Inheritance the "Old Way"

To make a Developer constructor inherit from Person, you had to perform several manual steps:

  1. Call the parent constructor (Person) from within the child constructor (Developer), ensuring this is correctly set using Person.call(this, ...).
  2. Set up the prototype chain so that Developer.prototype inherits from Person.prototype. The standard way to do this is Object.create(Person.prototype).
  3. Because the previous step overwrites Developer.prototype.constructor, you often need to reset it manually.

This process is complex and unintuitive.

How JavaScript Classes work under the hood

Let's return to the article 'How JavaScript Classes work under the hood' to see this complex process in full detail, followed immediately by its class-based equivalent. The contrast is very illuminating.

Read the sections 'Prototype chaining' and 'Classes in JavaScript'. Pay close attention to the multi-step process required to make Developer inherit from Human using constructor functions, and then see how the class and extends keywords simplify this down to a few lines.

Inheritance the "New Way"

With ES6 classes, this entire process is handled by the extends and super keywords.

class Developer extends Person {
  constructor(name, age, skillset) {
    // 1. Call the parent constructor to initialize 'name' and 'age'
    super(name, age);
    
    // 2. Add child-specific properties
    this.skillset = skillset;
  }

  code() {
    console.log(`${this.name} is coding using ${this.skillset}.`);
  }
}

const charlie = new Developer('Charlie', 35, 'Python and SQL');
charlie.greet(); // "Hello, my name is Charlie." (Inherited from Person)
charlie.code();  // "Charlie is coding using Python and SQL." (Own method)

The extends keyword automatically sets up the prototype chain (Developer.prototype will inherit from Person.prototype). The super() call within the constructor invokes the parent class's constructor. This is a massive improvement in readability and maintainability.

Test your understanding!

Here is a Vehicle implemented using the traditional constructor function pattern.

function Vehicle(make, model) {
  this.make = make;
  this.model = model;
}

Vehicle.prototype.getDetails = function() {
  return `${this.make} ${this.model}`;
};

Vehicle.prototype.startEngine = function() {
  console.log(`The engine of the ${this.model} is starting.`);
};

Your task is to:

  1. Refactor the Vehicle code above into an ES6 class.
  2. Create a Car constructor function that inherits from the original Vehicle constructor function. It should have an additional numDoors property.
  3. Refactor your Car implementation into an ES6 class that extends the Vehicle class you created in step 1.
Show answer

Step 1: Refactor Vehicle to an ES6 class

class Vehicle {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  getDetails() {
    return `${this.make} ${this.model}`;
  }

  startEngine() {
    console.log(`The engine of the ${this.model} is starting.`);
  }
}

Step 2: Car constructor inheriting the "old way"

function Car(make, model, numDoors) {
  // Call the parent constructor
  Vehicle.call(this, make, model);
  this.numDoors = numDoors;
}

// Set up the prototype chain
Car.prototype = Object.create(Vehicle.prototype);

// Reset the constructor property
Car.prototype.constructor = Car;

// Test it
const oldWayCar = new Car('Toyota', 'Camry', 4);
console.log(oldWayCar.getDetails()); // "Toyota Camry"
oldWayCar.startEngine(); // "The engine of the Camry is starting."
console.log(oldWayCar.numDoors); // 4

Step 3: Car class inheriting the "new way"

class Car extends Vehicle {
  constructor(make, model, numDoors) {
    // Call the parent constructor
    super(make, model);
    this.numDoors = numDoors;
  }
}

// Test it
const newWayCar = new Car('Honda', 'Civic', 4);
console.log(newWayCar.getDetails()); // "Honda Civic"
newWayCar.startEngine(); // "The engine of the Civic is starting."
console.log(newWayCar.numDoors); // 4

Notice how much more concise and intuitive the class/extends/super version is compared to the manual prototype manipulation.


Conclusion

Today we've drawn a clear line between JavaScript's foundational inheritance model and the modern syntax used to interact with it.

Key Takeaways:

  • JavaScript's object model is based on prototypal inheritance, where objects inherit properties and methods from other objects via a prototype chain.
  • The traditional pattern for this was using constructor functions for instance properties and adding shared methods to the function's .prototype property.
  • Inheriting with constructor functions was a verbose, manual process involving Function.prototype.call and Object.create.
  • The ES6 class syntax is syntactic sugar over this same prototype system. It provides a cleaner, safer, and more familiar syntax but does not change the underlying mechanism.
  • The extends keyword handles the complexities of setting up the prototype chain for inheritance automatically.

Next Up

Now that we have a solid understanding of how class syntax relates to the prototype chain, we can explore its features in more detail. In our next lesson, we will focus specifically on class inheritance, diving deeper into how to implement class inheritance using extends and correctly call parent constructors with super(), including the important rules you must follow when overriding constructors.