@Bergi bahsetti new.target.prototype, ancak aramaya gerek kalmadan erişebileceğinizi this(veya daha iyisi, müşteri kodunun oluşturduğu nesnenin referansına new, aşağıya bakın) kanıtlayan somut bir örnek arıyordum super().
Konuşmak ucuz, bana kodu göster ... İşte bir örnek:
class A {
constructor() {
this.a = 123;
}
parentMethod() {
console.log("parentMethod()");
}
}
class B extends A {
constructor() {
var obj = Object.create(new.target.prototype)
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)
Hangi çıktı:
parentMethod()
childMethod()
this === obj ? true
obj instanceof A ? true
obj instanceof B ? true
Eğer etkili bir türde bir nesne oluştururken görebilirsiniz Yani Baynı zamanda tip bir amacı (çocuk sınıfı) A(üst sınıfında) ve içindeki childMethod()çocuğun Bbiz sahip thisnesneyi işaret objbiz B'nin oluşturulan constructorile Object.create(new.target.prototype).
Ve bunların hepsini hiç umursamadan super.
Bu, JS'de constructor, istemci kodu ile yeni bir örnek oluşturduğunda tamamen farklı bir nesne döndürebileceği gerçeğinden yararlanır new.
Umarım bu birine yardımcı olur.