Problem
You want to define a static method inside a “class”.
Ingredients
- 1 “class”
- 1 method
- the
static
keyword
Directions
-
Create a “class”.
class SomeClass { constructor(property) { this.property = property; } }
-
Add a method to that class (at this moment it is not static).
class SomeClass { constructor(property) { this.property = property; } someStaticMethod() { console.log('someStaticMethod'); } }
-
Add the
static
keyword before the method name to make it static.class SomeClass { constructor(property) { this.property = property; } static someStaticMethod() { console.log('This is a static method'); } }
-
Voilá, there you got a static method.
SomeClass.someStaticMethod(); // "This is a static method"
Notes
-
Static methods cannot be called on an instance:
let instance = new SomeClass(); // instance.someStaticMethod(); // won't work
-
To call a static method based on an instance you need to call it via the
constructor
property:let instance = new SomeClass(); instance.constructor.someStaticMethod();