Object prototypes

Hello everyone

hope that everything going fine with all of you

i just notice that if you did the following

let person2 = Object.create(person1);

let person3 = person1;

console.log(person2);
person1.age=555;

console.log(person2.age);

console.log(‘hi’);

console.log(person3.age);

any change in any of the objects property will effect the other so that code make all object copied by reference not by value i.e all those object point to the same memory location not just 2 instance with same value

hope that help and have a nice day

Hey, console.log is misleading. According to MDN console.log:

many browsers provide a live view that constantly updates as values change. This may not be what you want.

If you use instead the recommended console.log(JSON.parse(JSON.stringify(obj)) you will see that Object.create does create a new object.

sorry looks like i did not explain my self as i should be

i did not said that it did not create new object

i meant all those object point to the same memory location that’s why a change in one or it’s member affect them all not just single one

hope that make it clear and have a nice day

They don’t point to the same memory location. console.log is misleading you.

const p1 = {a:1}; const p2 = Object.create(p1); 
console.log(JSON.parse(JSON.stringify(p1.a)); // 1
console.log(JSON.parse(JSON.stringify(p2.a)); // 1
p2.a = 2;
console.log(JSON.parse(JSON.stringify(p1.a)); // 1
console.log(JSON.parse(JSON.stringify(p2.a)); // 2

you right for
let person2 = Object.create(person1);

but for this
let person3 = person1;

person1.age=555;

console.log(JSON.parse(JSON.stringify(person3.age)));
console.log(JSON.parse(JSON.stringify(person1.age)));

both point to the same thing both print 555

Hello @chrisdavidmills

could you help us here

thanks for both of you and have a nice day

@justsomeone So, let me have a go at this.

I don’t really get the difference between console.log(JSON.parse(JSON.stringify(x))); and just console.log(x) — I just did a load of testing and couldn’t see any difference.

In the case of the question @justsomeone asked, it seems that when you do let person2 = Object.create(person1);, person2 is a different object, separate from person1.

Whereas is you do person2 = person1, person2is just a reference to the same object that is also stored in person1. Which is pretty much never what you want.

I don’t know, do you think I need to explain this somewhere? This is pretty obscure and confusing stuff :wink:

Thanks a lot @chrisdavidmills

i am not sure but if you can explain it in the learning stuff so people did not get tricked by it would be nice

and i agree it confusing :wink:

thanks again and have a nice day :slight_smile: