1

I'm confused why can't I take follwing code correctly make sense

function Parent(){
    this.foo = 'bar';
}

function Son(){}


// if I do this
Son.prototype = Parent.prototype;
new Son().foo;
// output undefined


// try normal way
Son.prototype = new Parent();
new Son().foo;
// output 'bar'

In my opinion, instance son find its prototype via __proto__, maybe like a pointer, but why can't I directly refer to Parent.prototype?

L.Jovi
  • 1,631
  • 4
  • 22
  • 36
  • @squint I don't think this question is a duplicate of that one. It's probably a duplicate of *something*, sure, but this question is asking why properties assigned to instances aren't visible thanks to the sharing of prototype objects. – Pointy Jul 17 '15 at 11:38
  • @Pointy: True. I was tripped up by his phrasing. –  Jul 17 '15 at 11:41

2 Answers2

2

There is no "foo" property on the "Parent" prototype object. The Parent() constructor puts a "foo" property on each instance constructed.

So you are successfully sharing the same prototype object between the two constructors, but that doesn't achieve what your code expects it to achieve.

If your code had explicitly added a "foo" property to the "Parent" prototype like this:

function Parent() {}
Parent.prototype.foo = "this is foo";

Then this would work:

function Son() {}
Son.prototype = Parent.prototype;
alert(new Son().foo); // "this is foo"

Now, sharing prototype objects is certainly something you can do, but it's kind-of unusual.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

As the this.foo is not in the prototype. It is unable to access in the first way. When you create an instance, that means son is having the foo object that was declared in parent.

For clear explanation on prototype Refer :http://javascriptissexy.com/javascript-prototype-in-plain-detailed-language/

bvakiti
  • 3,243
  • 4
  • 17
  • 26