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.
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.
- 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.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
file 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 ...