1

Possible Duplicate:
Self-references in object literal declarations

Hey Guys,

i have a small question regarding JavaScript Objects. I have the following Object in JavaScript:

var CONFIG = {
    MAIN_URL: 'http://www.test.us',
    MAIN_COLOR: '#fff'
}

now i want to declare an object with another object prefixed:

var CONFIG = {
    MAIN_URL: 'http://www.test.us',
    LOGIN_URL: MAIN_URL+'/login', // <- this one!
    MAIN_COLOR: '#fff'
}

how do i do that? I have tried with this.MAIN_URL, CONFIG[MAIN_URL], CONFIG.MAIN_URL - but nothing works?!?!

Thanks, Sascha

Community
  • 1
  • 1
codeworxx
  • 45
  • 1
  • 6

2 Answers2

6

You can't do that in an object initializer. Instead, do something like this:

var CONFIG = {};
CONFIG.MAIN_URL = 'http://www.test.us';
CONFIG.LOGIN_URL = CONFIG.MAIN_URL+'/login'; // <- this one!
CONFIG.MAIN_COLOR = '#fff';
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
4
var CONFIG = new function() {
    this.MAIN_URL = 'http://www.test.us',
    this.LOGIN_URL = this.MAIN_URL+'/login', // <- this one!
    this.MAIN_COLOR = '#fff'
};
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Hi Esailija, thanks for the fast response. This works :-) Amazing. Thanks again! – codeworxx May 26 '12 at 11:56
  • @codeworxx: It works, but it creates a lot more stuff than you need. Just `var CONFIG = {}; CONFIG.MAIN_URL = ...;` and such is no more verbose, and avoids unnecessarily creating and running functions. – T.J. Crowder May 26 '12 at 11:59
  • @T.J.Crowder if verbosity is a concern, then you can alias `this` to something at the top of function, which results in a better minification as well and the alias won't leak into current scope (global it seems) – Esailija May 26 '12 at 12:05
  • @Esailija Ew. I think that just makes the problem worse. – Kendall Frey May 26 '12 at 12:07
  • okay, thanks esailija, but i prefer kendalls method... – codeworxx May 26 '12 at 12:08