28

Possible Duplicate:
Self-references in object literal declarations

Is there any way access the value of a property name in the same object literal? Something like this:

myFunction.init({
    varOne: 'something',
    varTwo: this.varOne + 'something else'
})
Community
  • 1
  • 1
Adrian Florescu
  • 4,454
  • 8
  • 50
  • 74
  • 1
    Of course you can. With getters and setters or by creating function which then fix the scope of the object. Not sure why the other answer was picked – Oz Lodriguez May 08 '16 at 13:09
  • @OzLodriguez - why don't you post an answer to this or a link to a jsfiddle/codesandbox/etc? – Adrian Florescu Dec 13 '19 at 09:25
  • @AdrianFlorescu, @BlueYoshi posted an example in the comment on the accepted answer. But, there's a catch to this approach @OzLodriguez. `varTwo` in the original question will always update when `varOne` is changed with the getter approach. That is different from what I would expect the behavior to be in the question (assuming it was even possible). If the code in the question actually worked I would expect it to initialize `varTwo` with `varOne` once and not change `varTwo` if `varOne` is changed in the future. – stuckj Nov 17 '20 at 18:05

1 Answers1

37

No, there is no way to access the object literal that is currently being defined from within the definition itself.

If you want to set properties based on the values of other properties, then you either need to base them both on some external value (that is not a property itself) or run an initializer function after the object literal is defined that can set some properties based on the values of other properties.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Ok, thank you very much for the quick response! I'll have to create an external variable and access that within the object. – Adrian Florescu Sep 30 '12 at 08:31
  • 2
    For more examples, see: http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations?lq=1 – BlueYoshi Jun 10 '14 at 08:08