How to Create a Subclass in JavaScript

Creating a subclass in JavaScript involves extending a base class to inherit its properties and behaviors, allowing for the creation of a more specific version of the class. This process of defining subclasses enables a hierarchical relationship that embodies the principles of object-oriented programming.

What is subclassing in JavaScript?

Subclassing is the practice of creating a new class, known as a subclass, that inherits attributes and methods from another class, referred to as the superclass. This relationship allows for polymorphism and code reuse, where subclasses can override or extend the functionality of their superclasses.

Defining a base class

Before creating a subclass, you need a base class to extend from. Here's an example of a simple base class in JavaScript:

class Shape { constructor(color) { this.color = color; } describe() { return `A shape of color ${this.color}`; } }

Extending the base class to create a subclass

To create a subclass, use the extends keyword followed by the base class name. The subclass can then add its own properties and methods or modify existing ones.

class Circle extends Shape { constructor(color, radius) { super(color); this.radius = radius; } calculateArea() { return Math.PI * this.radius * this.radius; } }

Overriding methods in a subclass

Subclasses can override methods of their superclass to provide specialized behavior. The super keyword is useful to call functions on an object's parent.

class Square extends Shape { constructor(color, side) { super(color); this.side = side; } describe() { return `A square of color ${this.color} and side ${this.side}`; } }

Using the subclass

Once the subclass is defined, you can create instances of it and use them just like any other class:

let myCircle = new Circle('red', 5); console.log(myCircle.describe()); // 'A shape of color red' console.log(myCircle.calculateArea()); // Approximately 78.54 let mySquare = new Square('blue', 3); console.log(mySquare.describe()); // 'A square of color blue and side 3'

Handling constructors and method chaining

In JavaScript, when defining a subclass constructor, you have to call super() before using this. This calls the parent class' constructor, ensuring that the subclass is properly set up. Here is an example:

class Rectangle extends Shape { constructor(color, width, height) { super(color); this.width = width; this.height = height; } }

Static methods and properties

Static methods and properties are also inherited in JavaScript subclasses. However, they must be called on the class itself, not an instance of the class.

class Shape { static createDefaultShape() { return new Shape('no color'); } } class Triangle extends Shape { static createDefaultTriangle() { return new Triangle('green', 3); } } let defaultShape = Shape.createDefaultShape(); let defaultTriangle = Triangle.createDefaultTriangle();

Private and protected members

JavaScript now supports private class fields using a hash # prefix. These private fields are not accessible outside the class they are declared in, not even by subclasses.

class Shape { #privateId; constructor(color) { this.color = color; this.#privateId = Shape.#generateUniqueId(); } static #generateUniqueId() { return Math.random().toString(36).substr(2, 9); } }

Subclassing built-in classes

Subclassing built-in classes in JavaScript should be done with care, as these classes have inherent behaviors that may not be obvious at first glance.

class CustomArray extends Array { // Custom methods or properties }

Mixin patterns for multiple inheritance

JavaScript does not support multiple inheritance directly, but mixins can be used to simulate this functionality. A mixin is a class that offers certain methods that can be used by other classes without needing to be the parent class of those other classes.

let SerializableMixin = Base => class extends Base { serialize() { return JSON.stringify(this); } }; class Shape { constructor(color) { this.color = color; } } class Circle extends SerializableMixin(Shape) { constructor(color, radius) { super(color); this.radius = radius; } }

Best practices for subclassing

When subclassing, it's important to ensure that subclasses are a logical extension of their superclass. They should represent a more specific version of the superclass and adhere to the Liskov Substitution Principle, which states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Invite only

We're building the next generation of data visualization.