@Bergi ha menzionato new.target.prototype, ma stavo cercando un esempio concreto che dimostri che puoi accedere this(o meglio, il riferimento all'oggetto con cui sta creando il codice client new, vedi sotto) senza dover chiamare super().
Parlare costa poco, mostrami il codice ... Quindi ecco un esempio:
class A { // Parent
constructor() {
this.a = 123;
}
parentMethod() {
console.log("parentMethod()");
}
}
class B extends A { // Child
constructor() {
var obj = Object.create(new.target.prototype)
// You can interact with obj, which is effectively your `this` here, before returning
// it to the caller.
return obj;
}
childMethod(obj) {
console.log('childMethod()');
console.log('this === obj ?', this === obj)
console.log('obj instanceof A ?', obj instanceof A);
console.log('obj instanceof B ?', obj instanceof B);
}
}
b = new B()
b.parentMethod()
b.childMethod(b)
Che produrrà:
parentMethod()
childMethod()
this === obj ? true
obj instanceof A ? true
obj instanceof B ? true
Quindi puoi vedere che stiamo effettivamente creando un oggetto di tipo B(la classe figlia) che è anche un oggetto di tipo A(la sua classe genitore) e all'interno childMethod()di figlio Babbiamo thispuntato all'oggetto objche abbiamo creato in B constructorcon Object.create(new.target.prototype).
E tutto questo senza preoccuparsene superaffatto.
Ciò sfrutta il fatto che in JS a constructorpuò restituire un oggetto completamente diverso quando il codice client costruisce una nuova istanza con new.
Spero che questo aiuti qualcuno.