I found a solution while typing out this question, I will still post the question, since I couldn't find anything on this, if that isn't appreciated, I will remove this on request.
I've done it for a class that doesn't have subclasses like so:
export class SomeClass{
constructor(a, b){
this.a = a;
this.b = b;
this.args = arguments;
}
getDefault(){
return new SomeClass(...this.args);
}
};
This works satisfactorily for now. I'm aware that when passing a shallow copy of an object to the constructor, getDefault()
will be unable to recreate the initial values of that object's properties. That's an issue to be sorted out later (or might never actually be an issue).
Now I would love to inherit from this class and have all subclasses mirror this ability - but it appears to me that the superclass would need to be aware of any parameters a subclass might take, which somewhat defeats the purpose of using inheritance in the first place.
Solution:
export class SuperClass{
constructor(a, b){
this.a = a;
this.b = b;
this.args = arguments;
}
getDefault(){
return new this.constructor(...this.args);
}
};
export class SubClass extends SuperClass{
constructor(a, b, c){
super(...arguments);
this.c = c;
}
};
It should be noted that this passes a bunch of parameters the superclass doesn't know what to do with, which I'm unsure about how dirty this is considered in JavaScript. Also, this works because this
refers to the instance getDefault()
is called on, so this.constructor
calls the constructor of the subclass with the parameters previously stored when super(...arguments)
was called. I do not know how good of a solution this is.