Javascript 访问对象内的对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12789141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:16:53  来源:igfitidea点击:

Access object properties within object

javascriptobjectproperties

提问by Adnan

Possible Duplicate:
Access JavaScript Object Literal value in same object

可能的重复:
访问同一对象中的 JavaScript 对象文字值

First look at the following JavaScript object

首先看下面的JavaScript对象

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

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

我想设置birthplace与 相同的值country,所以我将对象值country放在前面birthplace但它对我不起作用,我也使用过this.country但它仍然失败。我的问题是如何在对象中访问对象的属性。

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

问候

回答by I Hate Lazy

You can't reference an object during initialization when using object literalsyntax. 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.

此示例使用匿名函数作为构造函数。新对象通过this.

var settings = new function() {
    this.user = "someuser";
    this.password = "password";
    this.country = "Country";
    this.birthplace = this.country;
};

回答by Joe

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
}