【问题标题】:Access object properties within object [duplicate]访问对象内的对象属性[重复]
【发布时间】:2012-09-29 03:23:47
【问题描述】:

可能重复:
Access JavaScript Object Literal value in same object

先看下面的JavaScript对象

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

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

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

任何帮助将不胜感激:)

问候

【问题讨论】:

标签: javascript object properties


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在使用 object literal 语法时,您不能在初始化期间引用对象。您需要在创建对象后引用它。

    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.国家, } } console.log(settings.birthplace); // 输出 -> 国家 ```
    • 要在es6中获取上面的代码,请在下面查看我的答案
    • @yukashimahuksay 因为这个问题很久以前就被关闭了。
    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2022-01-16
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多