Created
February 24, 2012 08:54
-
-
Save jameswestgate/1899587 to your computer and use it in GitHub Desktop.
JavaScript quick and dirty constants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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."; | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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