A while ago I wrote about how you can group related constants in PHP5 by using a constants class:
class MyConstants {
const AA = 'value';
const BB = 'another value';
}
echo MyConstants::AA; // output: value
Now, while experimenting with JavaScript (or more precisely with Node.js) I got some constants in my code I wanted to organize with such a constants class. My first, albeit naive, approach looked like:
var sys = require('sys');
function MyConstants() {
const AA = 'value';
const BB = 'another value';
}
sys.puts(MyConstants.AA); // output: undefined
However, as you can see, this doesn’t work. One reason is that const “[c]reates a constant that can be global or local to the function in which it is declared.”. So it isn’t possible to create a constants class like I imagined…
This means we have to emulate a constants class by using static properties and relying on the naming convention that names of constants are uppercased (i.e. the “constants” are technically not constants and their value can be changed):
var sys = require('sys');
function MyConstants() {
}
MyConstants.AA = 'value';
MyConstants.BB = 'another value';
sys.puts(MyConstants.AA); // output: value
If there is a better approach, please let me know.
Why not just use object literal syntax?
@Evan: Good question, I guess this is a good example of missing the wood for the trees… Thanks for pointing it out!
Isn’t the expression..”can’t see the forest for the trees”?
http://en.wiktionary.org/wiki/see_the_forest_for_the_trees
Ignore me – I saw the alternative listed in the link and you have it correct. Differences in location maybe…
@Abba: Probably differences between American and British English (I got the term from my dictionary).