JavaScript Static Variable ECMA6

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

For this, I read the following documentation:

The first link demonstrates how you can create static methods inside a class in ECMA 6, and the second link demonstrates how you can use prototype and functions to create static variables before ECMA6.

I don’t want any of this. 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 does not work because the static used only for methods.

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

0
source share
1 answer

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 using

 const defaultCarName = AutoMobile.DEFAULT_CAR_NAME; 

Class properties are not supported in ES2015.

+4
source

All Articles