83

Possible Duplicate:
Access JavaScript Object Literal value in same object

First look at the following JavaScript object

var settings = {
  user:"someuser",
  password:"password",
  country:"Country",
  birthplace:country
}

I want to set birthplace value same as country, so i put the object value country in-front of birthplace but it didn't work for me, I also used this.country but it still failed. My question is how to access the property of object within object.

Some users are addicted to ask "what you want to do or send your script etc" the answer for those people is simple "I want to access object property within object" and the script is mentioned above.

Any help will be appreciated :)

Regards

Shark Lasers
  • 441
  • 6
  • 15
Adnan
  • 1,379
  • 2
  • 17
  • 24
  • How's your country var defined? – Leniel Maccaferri Oct 08 '12 at 20:43
  • Duplicates: http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations, http://stackoverflow.com/questions/8036740/current-object-property-as-value-in-same-object-different-property, http://stackoverflow.com/questions/3173610/can-a-javascript-object-property-refer-to-another-property-of-the-same-object – user123444555621 Oct 08 '12 at 20:45

2 Answers2

101

You can't reference an object during initialization when using object literal syntax. You need to reference the object after it is created.

settings.birthplace = settings.country;

Only way to reference an object during initialization is when you use a constructor function.

This example uses an anonymous function as a constructor. The new object is reference with this.

var settings = new function() {
    this.user = "someuser";
    this.password = "password";
    this.country = "Country";
    this.birthplace = this.country;
};
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • 25
    Starting with ECMAScript 2015 you can now use [Javascript getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) and access the object within the object by doing: ``` const settings = { country: "Country", get birthplace() { return this.country, } } console.log(settings.birthplace); // outputs -> Country ``` – Nick Lucas May 14 '19 at 22:59
  • to get the above code in es6, please check my answer below – Rajesh Wolf Sep 23 '19 at 07:30
  • @yukashimahuksay because the question has been closed a long time ago. – m4heshd Apr 18 '21 at 17:45
2

You can't access the object inside of itself. You can use variable:

var country = "country";
var settings = {
  user:"someuser",
  password:"password",
  country:country,
  birthplace:country
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
Joe
  • 80,724
  • 18
  • 127
  • 145