Grouping “constants” with JavaScript

Published on and tagged with javascript

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.

5 comments baked

© daniel hofstetter. Licensed under a Creative Commons License