What would be the preferred way to create constants in javascript, specifically with ES6?
Currently I have a constants class which has methods that return the string I'm looking for.
class Constants {
constructor() {}
SOMECONSTANT() {
return 'someconstant';
}
}
-
1see Are there any OO-principles that are practically applicable for Javascript?gnat– gnat2015年05月28日 19:23:20 +00:00Commented May 28, 2015 at 19:23
1 Answer 1
For backwards compatibility, I would create a read-only property of the encapsulating object, which could be the global object:
Object.defineProperty(this, 'CONST', {
value: 123,
writable: false
});
See: Object.defineProperty - writable
attribute
Otherwise, ES6 has a const
keyword.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
See const.
answered May 28, 2015 at 19:30
-
My understanding with the const keyword is that it can only be used in local scope. I should have clarified I need the constants scoped globally.Beanwah– Beanwah2015年05月28日 21:26:18 +00:00Commented May 28, 2015 at 21:26
-
Local or global. It's block scoped, I think.svidgen– svidgen2015年05月29日 00:44:46 +00:00Commented May 29, 2015 at 0:44
lang-js