访问对象内的对象属性

Adn*_*nan 51 javascript properties object

可能重复:
访问同一对象中的JavaScript Object Literal值

首先看一下以下的JavaScript对象

var settings = {
  user:"someuser",
  password:"password",
  country:"Country",
  birthplace:country
}
Run Code Online (Sandbox Code Playgroud)

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

一些用户沉迷于询问"你想做什么或发送你的脚本等"这些ppls的答案很简单"我想访问对象中的对象属性",上面提到了脚本.

任何帮助将不胜感激 :)

问候

I H*_*azy 72

使用对象文字语法时,无法在初始化期间引用对象.您需要在创建对象后引用该对象.

settings.birthplace = settings.country;
Run Code Online (Sandbox Code Playgroud)

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

此示例使用匿名函数作为构造函数.新对象是参考this.

var settings = new function() {
    this.user = "someuser";
    this.password = "password";
    this.country = "Country";
    this.birthplace = this.country;
};
Run Code Online (Sandbox Code Playgroud)

  • 从ECMAScript 2015开始,您现在可以使用[Javascript getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)并通过执行以下操作访问对象内的对象: ``const settings = {country:“ Country”,get birthplace(){return this.country,}} console.log(settings.birthplace); //输出->国家(地区) (3认同)