It can be a good idea to organize methods on a class, rather than on an instance of a class. One example is the Manager pattern. This pattern is useful when an object is expensive to create, or will be reused a lot.
In this recipe, we'll see how to use the static
keyword to create a map for reusing instances of the Rocket
class.
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
07-07-static-methods-on-all-instances
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
file with an empty objectrocketMap
and a classRocket
:
//main.js let rocketMap = {}; class Rocket {}
- Create a static method named
find
that looks up rockets by string on theRocket
class:
class Rocket { // ...