@Bergi wspomniałem new.target.prototype, ale szukałem konkretnego przykładu udowadniającego, że możesz uzyskać dostęp this(lub lepiej, odwołanie do obiektu, za pomocą którego tworzy kod klienta new, patrz poniżej) bez konieczności wywoływania super().
Rozmowa jest tania, pokaż mi kod ... Oto przykład:
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)
Który wyświetli:
parentMethod()
childMethod()
this === obj ? true
obj instanceof A ? true
obj instanceof B ? true
Więc widać, że są skutecznie tworząc obiekt typu B(klasy dziecko), która jest również obiektem typu A(swojej klasie dominującej) oraz w ramach childMethod()dziecka Bmamy thisskierowaną do obiektu obj, który stworzyliśmy w B constructorz Object.create(new.target.prototype).
A wszystko to bez żadnej troski super.
Wykorzystuje to fakt, że w JS a constructormoże zwrócić zupełnie inny obiekt, gdy kod klienta konstruuje nową instancję z new.
Mam nadzieję, że to komuś pomoże.