Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define and reference constant value in object namespace?

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?

like image 463
RSG Avatar asked Oct 21 '22 16:10

RSG


2 Answers

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
        }
    }
})();
like image 100
dfsq Avatar answered Oct 24 '22 11:10

dfsq


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; 
})();
like image 42
gion_13 Avatar answered Oct 24 '22 11:10

gion_13