Unter ES6 habe ich eine Vererbungshierarchie
class A {}
class B extends A {}
Ich suche ein Analogon zu instanceof
für geerbte Klassen, z.B.
const X = B;
if (X extensionof A) {
console.log("X derives from A");
} else {
console.log(":(");
}
// I wish that this would log: "X derives from A",
// but `extensionof` is a syntax error.
Ich weiß nichts dergleichen extensionof
in ES6. Mein Bestes ist X === A || X.prototype instanceof A
für eine "gleiche oder Unterklasse von" Beziehung oder X.prototype instanceof A
für eine "Unterklassen" -Relation. Vermisse ich etwas Schöneres?
Antworten:
1 für die Antwort № 1Der einfachste Weg wäre wahrscheinlich
if (B.prototype instanceof A) ...
Sie könnten eine Funktion machen, wenn Sie wollten
function extensionOf(superClass, subClass) {
return subClass.prototype instanceof superClass;
}
if (extensionOf(A, B)) ...
@loganfsmyth erwähnt eine andere Lösung, die auch funktionieren würde
if (A.isPrototypeOf(B)) ...