Defining methods on a class
Classes that hold values are not particularly interesting. We also want them to be able to have some behaviors that act as interfaces to the outside world. In this recipe, we'll see how to add methods to a class.
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
07-03-defining-methods
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
with a class namedRocket
, which assigns aname
property upon construction:
// main.js class Rocket { constructor(name) { this.name = name; } }
- Add a method named
takeoff
that accepts an option countdown argument. The body of the method should log a message before and after a timeout:
// main.js class Rocket { // ... takeOff(countdown = 1000) {...