Interfaces and Abstract Classes in Javascript with ES6

Interfaces and Abstract Classes in Javascript with ES6

Recently while working on a refactor, I wanted to use ES6 classes
combined with polymorphism. For this, I needed an Abstract Class.
However, in Javascript ES6, Abstract Classes are not a standard. However,
there is a work around using the method below.

The Abstract Class

This class is the base Chat Reporter. The details aren’t super important,
but as you will notice, I create separate reporters that need to implement
the Flag method for flagging a chat.

class ChatReporter {
  constructor (message) {
     this.message = message;
  }

  flag () {
    throw new Error('You must implement this method');
  }
}

The Subclass

Now with the flag method throwing an error, this will force our subclasses
to implement, otherwise the compiler will throw an error.

class GroupChatReporter extends ChatReporter {
  constructor (message) {
     this.message = message;
  }

  flag () {
    db.flag(message);
  }
}

And that is it! This is a simplified version of what I actually implemented. If you want to see the real life example, checkout it out on Github:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s