5

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

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254

3 Answers3

10

You can use static getter:

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

console.log(HasStaticValue.MIN);
Morteza Tourani
  • 3,506
  • 5
  • 41
  • 48
4

You cannot reach your scope with ES6 unless static getter , however , you may can in ES7.

Anyway, Babel support now the wanted syntax (check http://babeljs.io/) :

class Foo {
  bar = 2
  static iha = 'string'
}

const foo = new Foo();
console.log(foo.bar, foo.iha, Foo.bar, Foo.iha);
// 2, undefined, undefined, 'string'
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
2

You'd need a method to return the attribute, otherwise its only accessible within the class, which defeats the point of what you're trying to do with static.

Shaun Sweet
  • 669
  • 5
  • 9