Skip to content

Instantly share code, notes, and snippets.

@jameswestgate
Created February 24, 2012 08:54
Show Gist options
  • Save jameswestgate/1899587 to your computer and use it in GitHub Desktop.
Save jameswestgate/1899587 to your computer and use it in GitHub Desktop.
JavaScript quick and dirty constants
(function() {
var constants = {}; //or window?
window.const = function() { //or possibly window._ with arg[0] being string = syntax or object literal as well
if (!args.length) return constants;
var value = constants[args[0]];
if (args.length === 1) return value;
if (typeof(value) === 'undefined') constants[args[0]] = args[1], return args[1];
throw "Constant already defined.";
}
})();
//Constant function - see above
var ALPHA = const("ALPHA", "A");
const("ALPHA = 'A'");
const({ALPHA: 'A'})
//Constant function with argument overloading and use of _ instead
_('ALPHA = "A"')
_({ALPHA: 'A'})
_.ALPHA
//Just use the window namespace but then nothing to stop you changing ALPHA ='B'
const('ALPHA', 'A');
const('ALPHA = "A"');
const({ALPHA: 'A'});
ALPHA
window.ALPHA
@jameswestgate
Copy link
Author

Quick and very dirty, hard to do it in a satisfactory way
All we want to do is define a value that is immutable
If we take the function route then may only start with $, _, or \unicode escape

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment