How to create static class constants in ES6

ES6 brings classes to JavaScript, but some things are not immediately obvious or entirely supported. For instance, there is no obvious way to create static class constants.

Here is the simplest way I have found to create constants:

class CurrentLocation {
  static get GEOLOCATION_ERROR() { return 'GEOLOCATION_ERROR'; }
  static get GEOLOCATION_REFUSED() { return 'GEOLOCATION_REFUSED'; }
  static get GEOLOCATION_ACQUIRED() { return 'GEOLOCATION_ACQUIRED'; }
  static get GEOLOCATION_PENDING() { return 'GEOLOCATION_PENDING'; }

  ...

  function isValid(){
    return this.status === CurrentLocationItem.GEOLOCATION_ACQUIRED
  }
}

In the example below, you can use CurrentLocation.GEOLOCATION_ERROR anywhere, but myGeolocationItem.GEOLOCATION_ERROR will not exist, as static members are not visible to class instances. Moreover, children of the CurrentLocation class will not inherit these attributes.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax