Z.B:
function A(){}
function B(){}
B.prototype = new A();
Wie kann ich überprüfen, ob die Klasse B die Klasse A erbt?
probieren Sie es aus B.prototype instanceof A
Sie können die direkte Vererbung mit testen
B.prototype.constructor === A
Zum Testen der indirekten Vererbung können Sie verwenden
B.prototype instanceof A
(diese zweite Lösung wurde zuerst von Nirvana Tikku gegeben)
zurück bis 2017:
Überprüfen Sie, ob das für Sie funktioniert
A.isPrototypeOf(B)
Gotchas: Beachten Sie, dass instanceof
nicht wie erwartet funktioniert, wenn Sie mehrere Ausführungskontexte/Fenster verwenden. Sehen §§ .
Per https://johnresig.com/blog/objectgetprototypeof/ ist dies eine alternative Implementierung, die mit instanceof
identisch ist:
function f(_, C) { // instanceof Polyfill
while (_ != null) {
if (_ == C.prototype)
return true;
_ = _.__proto__;
}
return false;
}
Wenn Sie es ändern, um die Klasse direkt zu prüfen, erhalten Sie Folgendes:
function f(ChildClass, ParentClass) {
_ = ChildClass.prototype;
while (_ != null) {
if (_ == C.prototype)
return true;
_ = _.__proto__;
}
return false;
}
instanceof
prüft selbst, ob obj.proto
f.prototype
ist, also:
function A(){};
A.prototype = Array.prototype;
[]instanceof Array // true
und:
function A(){}
_ = new A();
// then change prototype:
A.prototype = [];
/*false:*/ _ instanceof A
// then change back:
A.prototype = _.__proto__
_ instanceof A //true
und:
function A(){}; function B(){};
B.prototype=Object.prototype;
/*true:*/ new A()instanceof B
Wenn es nicht gleich ist, wird Proto mit Proto Proto im Check, Proto Proto Proto usw. ausgetauscht. Somit:
function A(){}; _ = new A()
_.__proto__.__proto__ = Array.prototype
g instanceof Array //true
und:
function A(){}
A.prototype.__proto__ = Array.prototype
g instanceof Array //true
und:
f=()=>{};
f.prototype=Element.prototype
document.documentElement instanceof f //true
document.documentElement.__proto__.__proto__=[];
document.documentElement instanceof f //false
Ich glaube nicht, dass Simon in seiner Frage B.prototype = new A()
bedeutete, weil dies sicherlich nicht der Weg ist, Prototypen in JavaScript zu verketten.
Vorausgesetzt, B erweitert A, verwenden Sie Object.prototype.isPrototypeOf.call(A.prototype, B.prototype)
.