Skip to content Skip to sidebar Skip to footer

Javascript And Referencing One Namespace Property From Another

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 ju

Solution 1:

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(){ returnthis._prop1 + ' you!' }
};

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

Solution 2:

You have to use this:

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

Solution 3:

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)

Post a Comment for "Javascript And Referencing One Namespace Property From Another"