1

Possible Duplicate:
Self-references in object literal declarations

How do I do the following:

var object = {
    alpha: 'one',
    beta: **alpha's value**
}

without splitting the object creation into two parts?

Community
  • 1
  • 1
Nick
  • 5,040
  • 8
  • 38
  • 69
  • Hmm.. well that stinks. I was trying to add enum types to my object like var object = { CURVETYPE: {DIRECT: 0, ROAD: 1}, travel: this.CURVETYPE.DIRECT }, but I can see this is going to ruin my nice namespace now... – Nick Aug 02 '10 at 21:53

4 Answers4

7

You can't, as noted. The closest equivalent is:

var object = new (function()
{
    this.alpha = 'one';
    this.beta = this.alpha;
})();

This uses a singleton instance created from an anonymous function. You can also declare private fields with var.

Matthew Flaschen
  • 268,153
  • 48
  • 509
  • 534
6

You can't, object literal syntax just doesn't support this, you'll have to create a variable first then use it for both, like this:

var value = 'one';
var object = {
  alpha: value,
  beta: value
};

Or...something entirely different, but you can't reference alpha when doing beta, because neither property has been created yet, not until the object statement runs as a whole is either accessible.

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
0

You cannot do that with {} object creation.

ndim
  • 33,404
  • 12
  • 45
  • 55
0

Another idea for a way to create that object, without cluttering the scope with any new variables:

var lit = function(shared) {
return {
    alpha: shared.v1,
    beta: shared.v2,
    gamma: "three", 
    delta: shared.v1

};
}(
 {
    v1: "one",
    v2: "two",
 }
);

One of those statements you're not sure how to indent....

Amitay Dobo
  • 1,372
  • 9
  • 11