2

I have a JavaScript class following the ECMA6 standard, and I would like to create a static variable in it.

To achieve this I read the following documentation:

The first link demonstrates how one can create static methods inside a class in ECMA 6, while the second link demonstrates how you can use prototype and functions to achieve the creation of static variables prior to ECMA6.

None of this is what I want. I am looking for something like this:

class AutoMobile {

    constructor(name, license) {
        //class variables (public)
        this.name = name;
        this.license = license;
    }

   //static variable declaration
   static DEFAULT_CAR_NAME = "Bananas-Benz";
}

However, the previous example wont work because the static keyword is for methods only.

How can I create a static variable inside a class in JavaScript using ECMA6 ?

Community
  • 1
  • 1
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266

1 Answers1

5

You can achieve this with getters:

class AutoMobile {

  constructor(name, license) {
    //class variables (public)
    this.name = name;
    this.license = license;
  }

  //static variable declaration
  static get DEFAULT_CAR_NAME() {
    return "Bananas-Benz";
  }
}

And access it with:

const defaultCarName = AutoMobile.DEFAULT_CAR_NAME;

Class properties are not supported in ES2015.

Audrius Lubys
  • 626
  • 6
  • 7
  • 3
    The easiest way to create a class property is to just assign it. They *are* supported, just not as part of the `class` syntax. – Bergi May 27 '16 at 10:05