0

I'd like to inherit some class MyClass from some built-in class Class in the conventional way, i.e. without the new "class" syntax. I'm used to the following:

MyClass.prototype = Object.create(Class.prototype);
function MyClass() {
   Class.apply(this, arguments); // calling the superconstructor => "TypeError: Class constructor: 'new' is required"
   ...
}
var myObject = new MyClass(...);

As indicated, for many newer classes, usage of "new" with the constructor is enforced (e.g. for MediaSource). But new will be used with MyClass and will already have created a new object, so that I should not create yet another object inside the constructor. What am I supposed to do, or what is the equivalent here of the super() call in the new class syntax?

The only way I could think of, is to indeed create an instance with new Class() and explicitly return this instance from the constructor. But then the prototype of MyClass (which might have additional properties) is not really used ...

Sebastian
  • 365
  • 3
  • 17
  • 1
    *"But `new` will be used with `MyClass` and will already have created a new object, so that I should not create yet another object inside the constructor."* That's unavoidable in this case I'm afraid, you end up throwing away the object that was originally created and using the one from your call to `Class` instead. Specifically, you do it with [`Reflect.construct`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct) (I'd probably pair it with a rest argument): `function MyClass(...args) { return Reflect.construct(Class, args, MyClass); }` – T.J. Crowder Jun 14 '22 at 10:08
  • 1
    (The third argument tells `Reflect.construct` what the subclass is; it's so that the new object gets `MyClass.prototype` as its prototype when it's created by the base class, `Class`.) – T.J. Crowder Jun 14 '22 at 10:08
  • Thanks, Reflect.construct seems really the natural way to go. However, assuming somebody would "like" to support IE-11 , one would need to do without Reflect.construct and therefore probably to manually redefine the prototype? Anyway, I've seen you had your comment previously as an answer and I was already about to accept it. So maybe you'd like to repost it as an answer ... – Sebastian Jun 14 '22 at 10:15
  • 1
    (I think the previous question's answers cover it.) You don't have this problem on platforms that don't have `Reflect.construct`, because they also don't have `class`. :-) So you could have a branch to handle both: `function MyClass() { if (typeof Reflect === "object" && Reflect && Reflect.construct) { return Reflect.construct(Class, arguments, MyClass); } Class.apply(this, arguments); }` *(that guard may be a bit OTT :-) )*. – T.J. Crowder Jun 14 '22 at 10:19
  • "*I'd like to inherit from some built-in class Class without the new "class" syntax.*" - this is impossible. – Bergi Jun 14 '22 at 11:10

0 Answers0