ArticleZip > How To Extend A Class Without Having To Use Super In Es6

How To Extend A Class Without Having To Use Super In Es6

If you've been diving into ES6 and wondering about subclassing without using the "super" keyword, you've come to the right place. Let's explore how you can extend a class without the need for "super" in ES6.

In ES6, extending a class without the "super" keyword can be achieved by using the "Object.assign()" method. This method allows you to mix the properties of different objects into a target object. In our case, we can use "Object.assign()" to create a new class that extends another class while avoiding the "super" requirement.

To extend a class without using "super" in ES6, you can follow these steps:

Step 1: Define the Parent Class
Begin by defining your parent class as you normally would in ES6. This class will serve as the base for the class you intend to extend without using "super".

Js

class ParentClass {
  constructor(property) {
    this.property = property;
  }

  parentMethod() {
    console.log('Method from the parent class');
  }
}

Step 2: Create the Extended Class
Next, create the class that will extend the parent class using the "Object.assign()" method. This method will copy the properties and methods from the parent class to the extended class.

Js

const ExtendedClass = Object.assign(
  {
    extendedMethod() {
      console.log('Method from the extended class');
    }
  },
  ParentClass.prototype
);

Step 3: Instantiate the Extended Class
Now that you have your extended class, you can instantiate it and use its methods just like you would with any other class in ES6.

Js

const instance = new ExtendedClass('example property');
console.log(instance.property); // Output: 'example property'
instance.parentMethod(); // Output: 'Method from the parent class'
instance.extendedMethod(); // Output: 'Method from the extended class'

By following these steps, you can extend a class in ES6 without the need for the "super" keyword. Keep in mind that while this approach allows you to achieve subclassing without "super", there are limitations to consider, especially when dealing with complex inheritance chains.

In conclusion, by leveraging the power of "Object.assign()" in ES6, you can extend a class without using the "super" keyword. This method provides a viable alternative for subclassing in situations where the traditional "super" keyword may not be suitable. Experiment with this approach in your projects and see how it can enhance your coding experience in ES6.