1

Possible Duplicate:
How can a Javascript object refer to values in itself?

Let's say I have:

var myNamespace = {
      _prop1: 'hello',
      _prop2: _prop1 + ' you!'
};

I'm just now finding out that this will error on _prop2 at load.

I can't understand why this doesn't work, I've worked around it in my code but I would still like to understand.

Community
  • 1
  • 1
Matt
  • 25,943
  • 66
  • 198
  • 303
  • 1
    Bear in mind that the thing you're declaring doesn't actually exist until the final }; in your code above because this isn't compiled - so the error you will get (_prop1 is undefined) is really telling you the entire truth of the matter! – Stephen Byrne Jan 28 '13 at 00:03
  • 1
    In javascript, variable scopes works a little bit differently than in C or other languages. When you ask for a variable, it checks if it as been declared as a var in the current scope (between the same brackets) or if it is a variable of the global object (window in a browser context). Here _prop1 as not been declared as a var in the same context, and so cannot be accessed. – Alexandre de Champeaux Jan 28 '13 at 00:09

3 Answers3

3

When you try and set prop2 the object hasn't initialised so the value of prop1 and mynamespace are both undefined.

There are a couple of ways to achieve what you want, one way would be to create prop2 as a function so it can dynamically get the value of prop1

var myNamespace = {
      _prop1: 'hello',
      _prop2: function(){ return this._prop1 + ' you!' }
};

Another way would be to set prop2 after myNamespace has been initialised

Coin_op
  • 10,568
  • 4
  • 35
  • 46
1

You have to use this:

var myNamespace = {
    _prop1: 'hello'
};
myNamespace._prop2: myNamespace._prop1 + ' you!';
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

Well, you can do

var myNamespace = {
      _prop1: 'hello',
      _prop2: myNamespace._prop1 + ' you!'
};

I don't think it's possible to do it any other way in the declaration (eg: using "self" or "this" doesn't work)

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
  • Actually I tried this as well and I still get an undefined error. It's really weird. Could it be chrome? I'll try a different browser and report back. – Matt Jan 27 '13 at 23:55
  • Nope, not in Firefox either – Matt Jan 27 '13 at 23:56
  • This would work if you did something like var myNamespace = {}; myNamespace = { _prop1: 'hello', _prop2: myNamespace._prop1 + ' you!' }; – Alexandre de Champeaux Jan 28 '13 at 00:31
  • This answer definitely doesn't work. You have to do it as a two-step process as per bfavaretto's answer. – nnnnnn Jan 28 '13 at 00:35