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

When running the following code on Node.js 4.2.1:

'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } util.inherits(MyDerived, MyClass); var d = new MyDerived(); 

I get the following error:

 constructor(name) { ^ TypeError: Class constructors cannot be invoked without 'new' 

I wonder if it is possible to inherit the old-style β€œJavaScript” classes from ECMAScript 6 classes? And, if possible, then how?

+7
javascript ecmascript-6
source share
1 answer

There really is no way out if you chose the class syntax.

The problem is that inheritance in ES6 is done by late initialization of the this with the return value from super() , which is a constructor call, for example, with new . The old "use" idiom ( .call() ) the parent constructor in the current "uninitialized" child instance works no more .

What else you can do is resort to "parasitic inheritance" - you have to explicitly build an instance, expand it and return it:

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

When you do this with new MyClass , you cannot set up the prototype correctly. To do this, 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 is an added benefit that MyDerived no longer needs to be called with new (if you supply MyDerived when new.target empty).

+8
source share

All Articles