0
function Person(name,age){
    this.name = name
    this.age = age;
}
Person.prototype.home = [1,2,3];
Person.prototype.aa =100;
var p = new Person('joy','7');


console.log(p.__proto__.home); //[1,2,3]
console.log(p.__proto__.aa); // 100

p.aa = 200; 
p.home[0] = 200; 

console.log(p.__proto__.home); //[200,2,3]
console.log(p.__proto__.aa); // 100 

Why p.__proto__.home was changed. In my opinion, the p.aa = 200; has changed the p.__proto__.aa,but it was not.

Why know the reason? Please write more details.
Which book is relevant to the content?

jiexishede
  • 2,473
  • 6
  • 38
  • 54

2 Answers2

2

When you are trying to access an attribute which does not exist on the object, Javascript will traverse up the prototype chain to find the attribute. However:

p.aa = 200

This assigns the attribute aa to the object directly. The object now as an attribute .aa, and it also still has .__proto__.aa as two independent attributes. You're not indirectly modifying the prototype by assigning to .aa.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • basically var p = {aa:200}, right with that line? we arent changing the prototype. (I'm not the op but just wondering) – Muntasir Alam Jul 12 '16 at 15:38
  • Well, you are *replacing* the object outright, which means it's also losing its `__proto__`... Ignoring that detail, yes, that's what you're doing. – deceze Jul 12 '16 at 15:39
  • What do you mean losing __proto_? – Muntasir Alam Jul 12 '16 at 15:41
  • You've just replaced the entire object by redefining `p` entirely. If it were `p.aa = 200` as in the OP's code, where the entire object isn't replaced, the fact that own properties added later won't overwrite properties already existing in the prototype chain is the issue – adeneo Jul 12 '16 at 15:42
  • @cresjoy OP's `p` has `p.__proto__.aa`. When you do `p = {..}`, that new `p` now doesn't have `p.__proto__.aa`. – deceze Jul 12 '16 at 15:43
  • Really? Wow, I totally did not know that. I thougt p.aa = 200, just adds a property aa with key 200, and leaves everything as is – Muntasir Alam Jul 12 '16 at 15:46
  • So is thee any way to keep the original proto, while adding in a property of aa? – Muntasir Alam Jul 12 '16 at 15:56
  • @cresjoy I think we're talking past each other. – deceze Jul 12 '16 at 16:28
0

p.__proto__.home has not been changed. The array that it references has been changed.

Ely
  • 10,860
  • 4
  • 43
  • 64