Access object properties within object [duplicate]

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

Answers:

Answer

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

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.