Neues Node.js-Buch
Alle Artikel

Define static properties using the class syntax

Problem

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

Ingredients

  • 1 “class”
  • 1 property

Directions

  1. Create a “class”.

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
    }
  1. Add the property that should be static directly to the “class”.

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
    }
    SomeClass.STATIC_PROPERTY = 'This is a static property.';
  2. Voilá, there you got your static property.

    console.log(SomeClass.STATIC_PROPERTY);  // "This is a static property."

Notes

  • Static properties cannot be accessed via an instance:

    let instance = new SomeClass();
    // console.log(instance.STATIC_PROPERTY);  // won't work
  • To access a static property based on an instance you need to access it via the constructor property:

    let instance = new SomeClass();
    console.log(instance.constructor.STATIC_PROPERTY);