@Bergi disebutkan new.target.prototype, tetapi saya sedang mencari contoh konkret yang membuktikan bahwa Anda dapat mengakses this(atau lebih baik, referensi ke objek yang dibuat dengan kode klien new, lihat di bawah) tanpa harus menelepon super()sama sekali.
Bicara itu murah, tunjukkan kodenya ... Jadi ini contohnya:
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)
Yang akan menghasilkan:
parentMethod()
childMethod()
this === obj ? true
obj instanceof A ? true
obj instanceof B ? true
Jadi Anda dapat melihat bahwa kita secara efektif membuat objek bertipe B(kelas anak) yang juga merupakan objek bertipe A(kelas induknya) dan di dalam childMethod()anak Bkita telah thismenunjuk ke objek objyang kita buat di B's constructorwith Object.create(new.target.prototype).
Dan semua ini tanpa peduli supersama sekali.
Ini memanfaatkan fakta bahwa di JS a constructordapat mengembalikan objek yang sama sekali berbeda ketika kode klien membuat instance baru dengan new.
Semoga ini bisa membantu seseorang.