I'd like to define a constant default value for a JS object and reference it in further declarations in the same namespace, a la:
var Foo = {
// 'constant' value for default key
DEFAULT_KEY : "COOKIE_MONSTER",
// a map declaration that should ideally reference the default key
key_map : {
a : Foo.DEFAULT_KEY,
b : Foo.DEFAULT_KEY
}
};
Foo
won't be defined before Foo.key_map, so Foo.DEFAULT_KEY
isn't a real thing.
What's the proper way to set / use these object constants?
The first pattern coming to my mind:
var Foo = (function() {
var DEFAULT_KEY = "COOKIE_MONSTER";
return {
DEFAULT_KEY: DEFAULT_KEY,
key_map: {
a: DEFAULT_KEY,
b: DEFAULT_KEY
}
}
})();
You could use an iife to return your desired object (namespace) :
var Foo = (function(){
var namespace = {};
namespace.DEFAULT_KEY = 'COOKIE_MONSTER';
namaespace.key_map = {
a : namespace.DEFAULT_KEY,
b : namespace.DEFAULT_KEY
};
return namespace;
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With