new instantiation design alternatives

Dmitry Lomov dslomov at chromium.org
Thu Sep 18 13:25:31 PDT 2014


On Thu, Sep 18, 2014 at 10:11 PM, Domenic Denicola <
domenic at domenicdenicola.com> wrote:

> From: es-discuss [mailto:es-discuss-bounces at mozilla.org] On Behalf Of
> Domenic Denicola
>
> > I'm just quoting Allen's gist. It's a base class whose constructor
> always throws (in the gist, by doing `this = undefined`). Almost all DOM
> classes are currently like this, for example.
>
> Actually, this is a really important point. Since HTMLElement is abstract
> (throws on construct in all cases), the *only* way of extending it is by
> doing `this = Object.create(new^.prototype)`. You *cannot* extend it with
> `this = new super()`, either implicitly or explicitly, since `new super()`
> throws.
>
> So if you want to extend HTMLElement, you will need `this =
> Object.create(new^.prototype)`, either implicitly or explicitly. (And I
> argue for implicitly.)
>

I see; thanks for explaining HTMLElement to me. I argue for explicitly, on
the following grounds. Imagine:

class A {
   constructor(x) { this.x = x; }
}

class B extends A {
   constructor(a, b) {
      this = new super(a+b);
      // do more
    }
}

Need to extent HTMLElement notwithstanding, I believe that since all Bs are
instances of As they must be properly initialized, which includes that 'x'
should be set on them. I assume that this is a majority case, more major
than HTMLElement.

If you implicitly do 'this = Object.create(new^.prototype)' you default
into wrong, un-initialized state for those base classes that actually
provide a constructor. It is very easy to make this mistake - just forget
the super call.

Same applies for extending many of exotic builtiins, such as RegExp and
TypedArrays. You just cannot create a typed array using
Object.create(Uint8Array.prototype). Same applied for constructible DOM
objects (Events etc).

It is just the truth that there is no one-size-fits-all, or even
one-size-fits-most way to call a super constructor, or more generally,
initialize an instance of a subclass. We should just embrace that there is
no good default here.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140918/ea1703df/attachment-0001.html>


More information about the es-discuss mailing list