Abdennour TOUMI Abdennour TOUMI - 11 days ago 5
Javascript Question

How to add static attribute to ES6 class

We know very well that

class
of ES6 brought also :
static
,
get
as well as
set
features :

However , it seems that
static
keyword is reserved only for Methods :

class Person {

// static method --> No error
static size(){
}
// static attribute --> with Error
static MIN=10;
}


How to be able to write
static
attribute within ES6 class to have something like the static attribute
MIN
.

We know that we can add the following instruction after class definition :

Person.MIN=10;


However , our scope is to find the way to write this instruction inside class block

Answer

You can use static getter:

class HasStaticValue {
  static get MIN() {
    return 10;
  }
}

console.log(HasStaticValue.MIN);

Comments