0

Below is the preparation code for explaining my concerns,

function Person(name) {  
  this.name = name;
}
Person.prototype.getname = function(){
return this.name;
}

function test(){}
test.prototype = new Person('why')

var p = new test();

console.log(p.getname()) // the outcome is ofcourse 'why'

p.__proto__.name = 'go'
console.log(p.getname()) // the outcome has been changed to 'go'

and here comes the problem.

test.prototype = new Person('goo')
console.log(p.getname()) // the outcome is still 'go' not 'goo'

why the outcome still 'go' not 'goo'?

is there any difference between

p.__proto__.name = 'go' vs test.prototype = new Person('goo')?

guess I`m now misunderstanding the internal operation systems.

need some help,

jwkoo
  • 2,393
  • 5
  • 22
  • 35
  • 1
    You changed `test.prototype` to a new object but the object `p` was constructed before this change, so the `p.__proto__` property still points to the old object. – abhishekkannojia Jul 12 '17 at 10:29
  • can you please explain more about "still points..?" rather not automatically points the changed object(test.prototype)? – jwkoo Jul 12 '17 at 10:47
  • i thought that the test.prototype has been changed, so theres no way p to point the old object, so automatically p inherit the new one. am i wrong? – jwkoo Jul 12 '17 at 10:48
  • 1
    The own properties of the instances are shadowing the properties with the same name in the prototype. Note, that `p.__proto__` is actually `Person.prototype`. – Teemu Jul 12 '17 at 10:52
  • Teemu thanks, but isn`t p.__proto__ equals to test.prototype? because p.__proto__.name exists, but Person.prototype.name does not exists, whereas test.prototype.name exists. – jwkoo Jul 12 '17 at 10:57

0 Answers0