ES6 Everyday: Extending Built-in Classes

Along with inheritance of our own classes, ES6 also offers us the ability to extend built-in classes.

One of the best use cases I’ve seen of this is Axel Rauschmayer’s example of extending the Error class:

class ParsingError extends Error
{
   // ...
}

A practice that is common in other languages, like Java and C#.

Of course, you can go far beyond this; this example from StackOverflow implements a stack by extending Array:

class Stack extends Array
{
   constructor(length)
   {
      super(length);
   }

   top()
   {
      return this[this.length - 1];
   }
}

According to the ES6 Compatibility Table, we should eventually have the option to extend all of the following built-in classes:

  • Array
  • Boolean
  • Error
  • Function
  • Map
  • Number
  • Promise
  • RegExp
  • Set
  • String

However, the ES6 Compatibility Table also shows us that this is basically unsupported across the board (a board that includes transpilers, browsers, and server runtimes), with a few small exceptions.

So, unfortunately, it’s a little too early to take this one out for a spin.