2

How do I define an object in javascript where the value of one of its key is inherited from another key.

a = {

  one : "a",

  two : this.one + 'b'

}

alert(a.two);

I know that I can do this by doing something like a.two = a.one + 'b';

But is there a cleaner way to keep them coupled within one flower brace

Atif
  • 10,623
  • 20
  • 63
  • 96

2 Answers2

2

You cannot access the properties of an object before it has been created (this includes during its creation).

I know that I can do this by doing something like a.two = a.one + 'b';

Yes

But is there a cleaner way to keep them coupled within one flower brace

No.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

You can't do it, at least not with a plain object literal.

Only functions have a valid this reference. Outside of a function this will refer to the global object (i.e. window).

Alnitak
  • 334,560
  • 70
  • 407
  • 495