I was wondering if it is possible to have mutually recursive objects in Javascript and, if so, how?
I want to have three objects:
Boolean
type with two values True
and False
True
object of Boolean
typeFalse
object of Boolean
typeThe trick is that I want to ask the True
object its type and I should get back Boolean
object and I want to ask a Boolean
object its values and I should get back 2 objects: the True
object and the False
object.
But it should be totally be mutually recursive in the sense that I get something like this (though it doesn't necessarily have to be exactly like this):
True
// {name : "True", type : [Object object]}
False
// {name : "False", type : [Object object]}
Boolean
// {name : "Boolean", values : [Object object]}
Boolean.values
// {True: [Object object], False: [Object object]}
True.type
// {name : "Boolean", values : [Object object]}
False.type
// {name : "Boolean", values : [Object object]}
Boolean.values.True
// {name : "True", type: [Object object]}
Boolean.values.True.type
// {name : "Boolean", values : [Object object]}
Boolean.values.True.type.values
// {True : [Object object], False: [Object object]}
and so on...
If it helps, they should satisfy the properties that:
Boolean === Boolean.values.True.type
Boolean === Boolean.values.True.type.values.True.type
True === Boolean.values.True
True === True.type.values.True.type.values.True.type.values.True
False === Boolean.values.False
False === True.type.values.False
and the ability to do this should be infinite
These could be functions instead of objects. And the calls don't have to be exactly like this.
Here you go:
//Define the top level objects but avoid recursion
var True = {};
var False = {};
var Boolean = {
values: {
True: True,
False: False
}
};
//Create the recursion
True.type = Boolean;
False.type = Boolean;