I’m having an issue getting the structure of my JS code right. I’m basically trying to create a complex object which contains other objects.
What I’m after is basically something like :
object {
f1: (),
f2: (),
objA: {
objA: {
v1: ""
}
},
objB: {
objA: {
v1: "",
v2: "",
f1: ()
}
}
}
Or something similar to this. I had something kinda of working, but in the object, I want to be able to reference other parts of the object.
So for instance, with the example above, I’d like to set the variable object.objA.objB.v1 to be equal to the value from object.objA.objA.v1
When I tried this, I just got an error saying it couldn’t access objA of undefined.
How can I get around this or restructure it to make it work?
Object literals are not self-referential. You cannot reference something that hasn’t been defined yet. This is why you’re getting an error.
What you can do is defer definition of self-referential properties after the structure has been initially defined.
So initially define your object:
Then:
Keep in mind that this won’t work for primitive types like numbers. This will work for objects that have references, like functions and other objects/arrays.