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/