Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript?

There’s not really a way out once you’ve opted in to class syntax.

The problem is that inheritance in ES6 is done by late-initialising the this keyword with the return value from super(), which is a constructor call like with new. The old idiom of “applying” (.call()) the parent constructor on the currently “uninitialised” child instance does work no more.

What you can still do is to resort to “parasitic inheritance” – you’ll have to explicitly construct the instance, extend it, and return it:

function MyDerived() {
  var derived = new MyClass('MyDerived');
  … // set up properties
  return derived;
}

When you do this with new MyClass, you won’t get the prototype set up correctly however. For that, you will need to use the new ES6 Reflect.construct function, which takes the child class as an optional third parameter:

function MyDerived() {
  var derived = Reflect.construct(MyClass, ['MyDerived'], new.target||MyDerived);
  … // set up properties
  return derived;
}

This has the additional benefit that MyDerived doesn’t need to be called with new any more (as long as you supply MyDerived when new.target is empty).

Leave a Comment