Is there a way to reuse the constructor of an already existing ES6 class to generate another? (Excuse my lack of OOP-phrases) What I like to achieve, is generating new classes on the run that merge already initialized ones, like a mixin but in a dynamic fashion. Here's how far I am:
function A(value){
this.a = value;
}
A.prototype.doA = function() {
console.log(this.a);
}
class B {
constructor(value){
this.b = value;
}
doB() {
console.log(this.b);
}
}
function morphed(OldClass){
let newClass = function(){
// ----------------------
// this throws an error on "B"
OldClass.prototype.constructor.call(this, ...arguments)
// ----------------------
this.c = 1;
}
const newPrototype = { doC: function(){ console.log(this.c) } }
newClass.prototype = Object.assign({}, OldClass.prototype, newPrototype);
return newClass;
}
const C = morphed(A);
const c = new C('123');
I know, that this example completely loses inherited functions of A or B, but thats ok for my usecase. Using the function based class "A", everything works fine, but when I try to access the constructor of "B" I get an error:
Cannot call a class as a function
how can I access the constructor of an already existing class as a function?
update: for those who asked, the goal is to inject something like inheritance, but without changing the initial classes. Kind of a mixin, but generated in runtime, so that multiple classes can be chained. Maybe this here explains it better:
const el = scrollable(draggable(collapsable(document.querySelector('.class') )));
const collapsable = function(el){
if(!el.isInitialized)
return new Collapsable(el);
else{
return injectPrototypeIntoPrototypeChain(el, Collapsable);
}
}
update 2:
Ok here's my last try: Maybe its just my misconception of JS's prototype chain, somehow I thought this should be possible: (The variable names are chozen independently from previous code snippets)
All my attempts have ended in babel telling me "Cannot call a class as a function" or overwriting the prototype chain of instance. So maybe my initial question should've been something like How can I append the prototype chain of an instantiated object to a new object with an own prototype chain?
@Bergi indeed this mixes up class and instance level. My problem with popular "mixin" patterns is that single properties can get overwritten and (as far as I understand) its hard to do Object.assign with objects that have i.e. 5 layers of inheritence.