Agata
Agata

Reputation: 554

Changing parent object , doesn't change prototype chain in other

I have two objects foo and bar. Object.create built object bar setting the prototype of it to foo - ok. When I update foo properties everything is ok, but when I change whole foo object for example to number, object bar does not change. As if the previous object foo was somewhere but I don't know where. I'm very curious about it.

var foo = { name: "foo" };
var bar = Object.create(foo);
foo = 2 //I change foo 
console.log(bar) 

//in Chrome console I see:
Object {}
__proto__: Object // __proto__ of bar shows to object 
   name: "foo"
  __proto__: Object

help. Maybe I miss something obvious.

Upvotes: 1

Views: 26

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68645

Because your foo is only reference to the object. When you set it as a prototype, it creates the second reference in the bar and refers to that same object. Then when you change the foo variable, which is only a reference to the object, to keep another variable like number, it removes the foo reference from the object. So you only have one reference which is in the prototype of the bar refering to the object.

[] is considered the value of the variable.

                        -----
  foo[obj address] ---> |obj|
                        -----
                          ^
                          |
                 bar.prototype[obj address]

After foo = 2

                        -----
   foo[2]               |obj|
                        -----
                          ^
                          |
                 bar.prototype[obj address]

Upvotes: 1

Related Questions