Using mix-ins to add behavior
We've seen how to use inheritance and composition to add behavior. There is a different method of composition that appends behavior onto existing classes without inheritance. Using mix-ins attaches properties to an object instance at runtime.
In this recipe, we'll see how to use the mix-ins to add shared behavior to classes without inheritance.
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-08-using-mixins. - 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, extend the current instance with an object namedLauncher:
// main.js
class Rocket {
constructor(name) {
Object.assign(this, Launcher);
this.name = name;
...