0

How can I assign a static property (constant) to my ES6 class?

Pseudo code about what I want to achieve:

class MyClass {

    static run() {
        // do something
    }

    static CONSTANT = {
        foo: "bar"
    }
}

MyClass.run(); // this works
console.log(MyClass.CONSTANT); // this sadly not

Which gives me the error:

Uncaught SyntaxError: Unexpected token =
Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59
  • 1
    [`The static keyword defines a static method for a class.`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static) – Pranav C Balan Jan 22 '17 at 15:51
  • How about using `Object.defineProperty(MyClass, "CONSTANT", {value: {foo:"bar"}})` –  Jan 22 '17 at 15:55

1 Answers1

0

The class syntax only allows method definitions. But you can assign the property outside:

class MyClass {}
MyClass.CONSTANT = {
  foo: "bar"
};
console.log(MyClass.CONSTANT); // this works
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • This is not a constant. It's reassignable. – Sebastian Barth Jan 22 '17 at 15:57
  • @TedBarth Well, just define it as non-enumerable non-writable. There is no such a thing as a constant property, only constant bindings. And it seems you are confused by the difference between static and constant. – Oriol Jan 22 '17 at 15:59