29

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'
})
3
  • 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 Commented May 8, 2016 at 13:09
  • @OzLodriguez - why don't you post an answer to this or a link to a jsfiddle/codesandbox/etc? Commented Dec 13, 2019 at 9: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. Commented Nov 17, 2020 at 18:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, thank you very much for the quick response! I'll have to create an external variable and access that within the object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.