new instantiation design alternatives

Allen Wirfs-Brock allen at wirfs-brock.com
Thu Sep 18 13:26:18 PDT 2014


On Sep 18, 2014, at 1:11 PM, Domenic Denicola 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.)

But that won't give you a real HTMLElement exotic object, if there is such a thing, and won't initialize it properly.

But you can get around that problem if the HTMLElement constructor is defined appropriately using this^:

class HTMLElement {
   constructor(...args) {
      if (this^ === HTMLElement) then throw new DOMError("can't create using new");
      if (this !== undefined) {
         //assert: must have been called via new super()
         this = privateAllocatedDOMElement();
         //initialize newly allocated DOMElement
      }
   }
}

Allen


More information about the es-discuss mailing list