Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  99] [ 1]  / answers: 1 / hits: 17048  / 5 Years ago, sun, november 3, 2019, 12:00:00

I have this object:



const obj = {
thing: 5,
layer: {
otherThing: obj.thing - 2
}
}


error:



ReferenceError: Cannot access 'obj' before initialization


I tried to use this but it didn't work as expected.


More From » node.js

 Answers
21

This is not something you can do in JavaScript. But you have two possible alternatives here:



1)



    const obj = {thing: 5, layer: {}};
obj.layer.otherThing = obj.thing - 2;


2) getters



    const obj = {
thing: 5,
layer: {
get otherThing(){obj.thing - 2}
}
}

[#51517] Thursday, October 24, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;