ES6 static class constants?


#1

Hi guys,

this is totally newbieish, BUT how do you guys define class constants in ES6?

… something like this would be nice & clean: (but throws errors)

class Tester {
  CONSTANT = 'a value';  // this throws an error

  do() {
    console.log(Tester.CONSTANT);    
  }
}

console.log(Tester.CONSTANT);

#2

contants like such:

const CONSTANT = 'a value';

statics

class Tester {
    static get CONSTANT() {
      return 'a value';
    }
}

#3

I also find this pretty annoying. You have to declare constants outside the class or attach them to the class later.

class Tester {
  do () {
    console.log(Tester.CONSTANT);
  }
}

Tester.CONSTANT = 'foo';

#4

Yeahhh - thats the one… and it is ugly as hell!!!
It makes me think about switching to CoffeeScript again. :smile:
But at least we can do something like:

// Namespace
Ns = {}

Ns.Tester = class Tester {
  static get CONSTANT_1() { return 'ohaa1'; }
  static get CONSTANT_2() { return 'ohaa2'; }
  static get CONSTANT_3() { return 'ohaa3'; }

  constructor() {
    console.log('constructor');
    console.log(Tester.CONSTANT_1);
    console.log(Tester.CONSTANT_2);
    console.log(Tester.CONSTANT_3);
  }
}

#5

Well… you can’t do this in ES6 but you can do it in ES7 if you’re ok living on the edge. It’s under the Babel stage 0 flag aka ‘experimental’. Otherwise static properties have to be defined as @mnmtanish mentioned.

Example in Babel REPL


#6

Hi @SkinnyGeek1010: thanks for the hint. But I really think it’s not too good to live “on the edge”. Hehe…

OK guys, so just out of intereset, which one do we pick?

Option 1:

Option 2:

I think I will stick with Option 1. :smile:
… or switch to Coffescript… someday. :smile:


#7

What’s the use case for class constants in JS ?