0

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

I'm creating an object like this:

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

However the current: this.all[1] returns undefined. I know full well that I can create the current property like this:

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

But I think this is quite messy, especially when creating multiple properties that need to reference their own object.

I've tried using both

  • current: this.all[1] (returns undefined) and
  • current: lines.all[1] (says lines doesn't exist)

How can I reference properties of the object I'm currently "in"? For instance, in my first example lines.current would be assigned the second element from lines.all.

Community
  • 1
  • 1
Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • related: http://stackoverflow.com/questions/8172111/can-i-alias-a-key-in-an-object-literal/8172171#8172171 – zzzzBov Sep 14 '12 at 14:02

2 Answers2

3

There is just one other solution than the one you posted:

var lines = new function() {
    this.all = [ /* Array */ ];
    this.current = this.all[1];
};
Vincent Thibault
  • 601
  • 5
  • 16
  • I was hoping there would be a "cleaner" solution, but I guess there isn't. I could've used a getter function, but that's even messier and doesn't lend well to debugging with `console.log()`. – Bojangles Sep 14 '12 at 14:13
  • this i think is slightly different from the question as lines in this case is closer to class in OOP than to object – Parv Sharma Sep 14 '12 at 14:14
  • @Parv I'm not too bothered really; this solution returns an object which is all I'm worried about. – Bojangles Sep 14 '12 at 14:19
0

because current is probably just a getter
you should according to some conventions change the name to getCurrent() as the top element in the array might change
and change your code to something like this.

var lines = {
    all: [ /* Array */ ],
    getCurrent: function(){return this.all[1];}
}
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • This is a good solution in that it keeps everything inside the object, however it doesn't debug that well with `console.log()`, so I've decided to use `new function()` instead. – Bojangles Sep 14 '12 at 14:14