Access JavaScript Object Literal value in same object [duplicate]
Asked Answered
P

1

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'
})
Parnassus answered 30/9, 2012 at 8:22 Comment(3)
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 pickedDasher
@OzLodriguez - why don't you post an answer to this or a link to a jsfiddle/codesandbox/etc?Parnassus
@AdrianFlorescu, @Sequestered 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.Croat
M
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.

Medwin answered 30/9, 2012 at 8:26 Comment(2)
Ok, thank you very much for the quick response! I'll have to create an external variable and access that within the object.Parnassus
For more examples, see: #4616702Sequestered

© 2022 - 2024 — McMap. All rights reserved.