javascript - 从自身内部访问当前对象

标签 javascript object

Possible Duplicate:
Self-references in object literal declarations
Can you call data from it's own json object?

我正在创建一个像这样的对象:

var lines = {
    all: [ /* Array */ ],
    current: this.all[1]
}

但是current: this.all[1]返回undefined 。我完全知道我可以创建 current像这样的属性:

var lines = {
    all: [ /* Array */ ]
}
lines.current = lines.all[1];

但我认为这相当困惑,尤其是在创建多个需要引用自己对象的属性时。

我尝试过同时使用

  • current: this.all[1] (返回 undefined )和
  • current: lines.all[1] (说 lines 不存在)

如何引用我当前“所在”对象的属性?例如,在我的第一个示例中 lines.current将被分配 lines.all 中的第二个元素.

最佳答案

除了您发布的解决方案之外,还有另一种解决方案:

var lines = new function() {
    this.all = [ /* Array */ ];
    this.current = this.all[1];
};

关于javascript - 从自身内部访问当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426022/

相关文章:

Javascript数组,修改所有键的值

javascript - 在Processing.js中,如何声明对象类型和对象数组?

javascript - jQuery 对象 - 值 = 值 + 数字 - 不起作用?

JavaScript - 递归构建树形数据结构

javascript - 使用 jquery 向非 native 服务器发送授权 header 时出错

javascript - 如何使 RNRF 中的自定义导航栏透明

javascript - 自定义 parcats plotly.js 图表的悬停

javascript - 由于相机位置,无法在场景中显示三个.js 元素

javascript - 条件中可能的异步调用

javascript - 通过映射为对象的属性赋值