Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 237
Adnan Avatar asked Oct 08 '12 20:10

Adnan


People also ask

How do you copy properties from one object to another JS?

Assigning. The Object. assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable.


2 Answers

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;
};
like image 68
I Hate Lazy Avatar answered Oct 04 '22 18:10

I Hate Lazy


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
}
like image 41
Joe Avatar answered Oct 03 '22 16:10

Joe