访问对象内的对象属性

IT技术 javascript object properties
2021-01-12 20:48:13

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

首先看下面的JavaScript对象

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

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

一些用户沉迷于问“你想做什么或发送你的脚本等”,这些人的答案很简单“我想访问对象内的对象属性”,上面提到了脚本。

任何帮助将不胜感激 :)

问候

2个回答

使用对象字面量语法时,您不能在初始化期间引用对象创建对象后,您需要引用该对象。

settings.birthplace = settings.country;

在初始化期间引用对象的唯一方法是使用构造函数。

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

var settings = new function() {
    this.user = "someuser";
    this.password = "password";
    this.country = "Country";
    this.birthplace = this.country;
};
从 ECMAScript 2015 开始,您现在可以使用Javascript getter并通过执行以下操作访问对象内的对象:``` const settings = { country: "Country", getbirthplace() { return this.country, } } console.log(settings 。出生地); // 输出 -> 国家 ```
2021-03-29 20:48:13
要在 es6 中获取上述代码,请查看下面我的回答
2021-03-29 20:48:13
@yukashimahuksay 因为这个问题很久以前就已经结束了。
2021-04-01 20:48:13

您无法访问其内部的对象。您可以使用变量:

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