3

I've seen some proposals for ECMAScript Harmony in terms of being able to specify constants with the keyword const. However, it seems to be only available in block scopes (i.e., FunctionBody and Program). Is there a way to define constants as an object property (imagine myObj.STATUS_OK)?

I guess the suggested way is to use properties via Object.definePropert(y/ies), but that does not seem very convenient, now is it?

Charles
  • 50,943
  • 13
  • 104
  • 142
Tower
  • 98,741
  • 129
  • 357
  • 507

2 Answers2

6

It seems that const is more related to environment frame bindings, and is thus a slightly different beast to objects and properties.

That said, on globals that's exactly what it does:

const a = 10;
Object.getOwnPropertyDescriptor(window, "a");
/*
   Object:
      configurable: true,
      enumerable: true
      value: 10
      writable: false
*/

If you're looking for shorthand then you can make a pretty simple macro.

In your case, an alternative would be to have a get-only value:

var myObj = {
   get STATUS_OK(){ return 42; }
};
davin
  • 44,863
  • 9
  • 78
  • 78
1

Just an idea.

Declare them as:

var CONST = 
 {
   ONE: 1,
   TWO: 2
 };

Object.seal(CONST);

And use them as:

   CONST.ONE, CONST.TWO 
c-smile
  • 26,734
  • 7
  • 59
  • 86