Вопрос

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.

Другие советы

Open the Object view and make sure they're actually the same... running your code (a few times... because of the weird recursion) gives me

>terah.spouse.spouse
age: 32
hairColor: "brown"
height: 66
name: "Terah"
spouse: Object
name: "Adam"
spouse: undefined //undefined
__proto__: Object
weight: 125
__proto__: Object
>terah
age: 32
hairColor: "brown"
height: 66
name: "Terah"
spouse: Object
name: "Adam"
spouse: Object //not undefined! so they ARE different!
__proto__: Object
weight: 125
__proto__: Object

See? two object were created. the real terah and an earlier 'version' of terah.

Have you tried just setting adam.spouse = terah?

At the time that you define adam, the object for terah doesn't exist, so at that time, terah.spouse is undefined. If you were to define Adam's spouse after defining Terah, you would get the result you are looking for:

var adam = {
    name: "Adam",
}

var terah = {
    name: "Terah",
    age: 32,
    height: 66,
    weight: 125,
    hairColor: "brown",
    spouse: adam
}

adam.spouse = terah

console.log(terah.spouse.spouse === terah) //true
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top