I can't figure this out...
I have two simple objects defined:
var adam = {
name: "Adam",
spouse: terah
}
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 125,
hairColor: "brown",
spouse: adam
}
The only property I'm concerned with is the spouse property. When I test:
console.log(terah.spouse.spouse);
> Object {name: "Terah", age: 32, height: 66, weight: 125, hairColor: "brown"…}
I get the object I want here. But when I make it a conditional
terah.spouse.spouse === terah;
>false
I get false... Why is this? It seems to be pointing to the same object. Even when I call
terah.spouse.spouse.name === "Terah"
>true
I get true there. Why do I get false with the object conditional? Thanks.`
The only way to actually make that work is:
var adam = {
name: "Adam"
};
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 125,
hairColor: "brown"
};
adam.spouse = terah;
terah.spouse = adam;
It's not an error to reference the variable "terah" in the object literal initializing "adam" (thanks to the hoisting of var
declarations), but at the point the code is evaluated the value of "terah" will be undefined
. The fact that it's later given a value doesn't matter.
(The object literal for "terah" could refer to the "spouse" property of "adam", but I split that out for clarity.)
Note that a circular reference like this won't be serializable as JSON. It might not throw an exception, but there's no way to represent a cycle like that in JSON.