Using static methods to work with all instances
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.
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-07-static-methods-on-all-instances. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js.
- Create a
main.jsfile with an empty objectrocketMapand a classRocket:
//main.js
let rocketMap = {};
class Rocket {} - Create a static method named
findthat looks up rockets by string on theRocketclass:
class Rocket {
// ...