Neues Node.js-Buch
Alle Artikel

Define static methods using the class syntax

Problem

You want to define a static method inside a “class”.

Ingredients

  • 1 “class”
  • 1 method
  • the static keyword

Directions

  1. Create a “class”.

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
    }
  1. Add a method to that class (at this moment it is not static).

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
      someStaticMethod() {
        console.log('someStaticMethod');
      }
    }
  2. 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');
      }
    }
  3. 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();