Using composition rather than inheritance to add behavior
So far, we've seen how to use inheritance to add behavior and compose larger structures. This is not always the ideal approach. In many situations, it's better to use a method known as composition instead. This involves using distinct classes in connection without establishing a hierarchical relationship. The chief advantage here is code clarity and flexibility.
In this recipe, we'll see how to use composition.
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-06-using-composition-instead-of-inherritence
. - 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
. Add a constructor that takes a constructor argumentname
and assigns...