0

Now the Child's prototype isn't actually a copy/reference of the Parent's prototype but rather the Child's prototype's prototype is. Parent prototype properties cannot even be overriden using the practical Child.prototype.foo = blah syntax, just shadowed, which seems like a waste of memory at best.

Why the added level of indirection instead of just using a flat copy/reference?

hubzkq1
  • 63
  • 5
  • What would a flat copy look like? – Ry- Feb 02 '15 at 00:20
  • Yes, they cannot be overridden. That they're only shadowed is the whole purpose of this construct. Imagine what would happen otherwise if you had multiple subclasses. – Bergi Feb 02 '15 at 00:21
  • @Bergi, no they would not be overriden, merely shadowed – hubzkq1 Feb 02 '15 at 00:24
  • But to answer my own question: probably because with a copy changes on the Parent prototype wouldn't propagate to the children any longer and with a reference changing the children's prototype would affect the Parent prototype, which is undesired. Right? Still effectively using the Child's prototype's prototype seems like a weird extra level of indirection. – hubzkq1 Feb 02 '15 at 00:24
  • @hubzkq1: Yes, that sounds about right. With a copy, changes on the parent would not be propagated (and there is no more inheritance), with a direct reference any change would affect the parent prototype directly which is undesired. – Bergi Feb 02 '15 at 00:28
  • *"Parent prototype properties cannot even be overriden"* That's the whole point. A change to a child class should not affect the parent. Just like Bergi mentioned. – Felix Kling Feb 02 '15 at 00:29
  • @FelixKling no I mean when you do `Child.prototype = Object.create(Parent.prototype)` where `Parent.prototype.foo` exists and then doing `Child.prototype.foo = blah`, then actually still `Child.prototype.prototype.foo == Parent.prototype.foo` even if `Parent.prototype.foo != blah` hence the original `foo` didn't get overriden, it is just shadowed – hubzkq1 Feb 02 '15 at 00:30
  • @FelixKling basically there are two points that are equally important it seems, like I said in my own answer. Because "Parent prototype properties cannot even be overriden" can be guaranteed with a copy too. Sometimes asking a question helps answering it I guess ^^ – hubzkq1 Feb 02 '15 at 00:33
  • @Bergi, right, makes sense now – hubzkq1 Feb 02 '15 at 00:33
  • Ah yes, I was focused on the referencing part only :) – Felix Kling Feb 02 '15 at 00:34
  • The easiest way to explain is to say a Cat is an Animal but an Animal isn't always a Cat. As for shadowing; you use this to deliberately completely override Parent with different behavior or extend Parent behavior. Not shadowing means you'll leave implementation up to the Parent. More detailed examples (although not a very good one) about extending can be found here: http://stackoverflow.com/a/16063711/1641941 – HMR Feb 02 '15 at 01:34

0 Answers0