Using throw to simulate abstract classes
So far, we've seen how to create and combine classes into a variety of different shapes. Sometimes, however, we want to be able to prevent the creation of a class and only allow instances of extending classes. Other languages provide a facility known as abstract classes. In this recipe, we'll see how to simulate this by throwing errors.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command line application and navigate to your workspace.
- Create a new folder named
08-10-use-throw-to-simulate-abstract-class. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js.
- Create a
main.jsfile that defines a new class namedRocket. In the constructor, check the constructor of the instance, if it'sRocket, then throw an error:
// main.js
class Rocket {
constructor (name) {
this.name ...