1

In <JavaScript: The Good Parts>, Douglas introduced the so called "pseudoclassical" pattern as one of the way to achieve inheritance. However, it seems the example he gives can not achieve inheritance of member variables, since prototype inheritance will not create copies of "superclass" variables when the "subclass" is constructed.

For a concrete example, let's consider two classes: a InputStream class that handles a underlying input mechanism as well as provides a simple read interface to read byte by byte; and a Utf8InputStream class that inherits InputStream and provide a readUtf8 interface to read a valid UTF8 character. It then seems problematic under the "pseudoclassical" pattern as all the Utf8InputStream will share the same underlying InputStream and things will obviously break.

It seems to me that using composition instead of inheritance will easily solve the problem, but just out of curiosity, is there anyway to achieve the inheritance of member variables here?

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
user690421
  • 422
  • 1
  • 5
  • 15
  • Might be helpful: The same Doug talking about power constructor and inheritance - @25min 10sec: https://www.youtube.com/watch?v=DwYPG6vreJg – sanchez Mar 27 '14 at 23:02

1 Answers1

1

It then seems problematic under the "pseudoclassical" pattern as all the Utf8InputStream will share the same underlying InputStream and things will obviously break.

No, that just happens when you're doing it wrong and create an instance for the prototype. Correct:

function Utf8InputStream(…) {
    InputStream.call(this, …);
    …
}
Utf8InputStream.prototype = Object.create(InputStream.prototype);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375