Access object properties within object

JavascriptObjectProperties

Javascript Problem Overview


> 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

Javascript Solutions


Solution 1 - Javascript

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;
};

Solution 2 - Javascript

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdnanView Question on Stackoverflow
Solution 1 - JavascriptI Hate LazyView Answer on Stackoverflow
Solution 2 - JavascriptJoeView Answer on Stackoverflow