I am making a library where I would like to provide a helper to extend the base class so that users can extend it even if they are not using ES2015 themselves. The issue is that if the base class happens to be in ES2015 (because it isn't sent through transpiler), my calling of parent constructor from subclass fails with:
Class constructor Foo cannot be invoked without 'new'
Example of what I am trying to achieve:
class Foo {
constructor() {
console.log("In Foo");
}
superMethod() {
return console.log("In super method");
}
static classMethod() {
return console.log("In class method");
}
}
Foo.extendClass = function (constructor, methods) {
const currentClass = this;
if (typeof constructor !== 'function') {
methods = constructor;
constructor = function () {
return Object.getPrototypeOf(constructor).apply(this, arguments);
};
}
constructor.prototype = Object.create(currentClass.prototype, {
constructor: {
value: constructor,
writable: true,
configurable: true
}
});
Object.setPrototypeOf(constructor, currentClass);
Object.assign(constructor.prototype, methods);
return constructor;
};
const Bar = Foo.extendClass({
subMethod: function() {
return console.log("In sub method");
}
});
b = new Bar();
The problem is in this line:
return Object.getPrototypeOf(constructor).apply(this, arguments);
So how can I call into parent's constructor? I thought ES2015 are just a sugar on top of standard prototype inheritance, but it looks like you cannot simulate it? Is there another way to define subclasses at run time?