javascript - Why can't I assign Parent.prototype to Son.prototype -


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

function parent(){     this.foo = 'bar'; }  function son(){}   // if son.prototype = parent.prototype; new son().foo; // output undefined   // try normal way son.prototype = new parent(); new son().foo; // output 'bar' 

in opinion, instance son find prototype via __proto__, maybe pointer, why can't directly refer parent.prototype?

there no "foo" property on "parent" prototype object. parent() constructor puts "foo" property on each instance constructed.

so sharing same prototype object between 2 constructors, doesn't achieve code expects achieve.

if code had explicitly added "foo" property "parent" prototype this:

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

then work:

function son() {} son.prototype = parent.prototype; alert(new son().foo); // "this foo" 

now, sharing prototype objects can do, it's kind-of unusual.


Comments