Mit dem Operator instanceof testen Sie nicht, ob etwas von einem bestimmten Konstruktor erstellt wurde, sondern ob etwas von einem bestimmten Objekt erbt (ob ein bestimmtes Objekt in der Prototypkette von etwas ist). foo Instanceof F hat genau das gleiche Ergebnis wie eine rekursive * Object.getPrototypeOf(foo) === F.prototype
var F = function() {};
var foo = new F();
foo instanceof F // true
Object.getPrototypeOf(foo) === F.prototype // true
F.prototype = {}; // changed the prototype of F
foo instanceof F // false
Object.getPrototypeOf(foo) === F.prototype // false
foo instanceof Object // true
Object.getPrototypeOf(Object.getPrototypeOf(foo)) === Object.prototype // true
Vor diesem Hintergrund ist es ziemlich offensichtlich, dass, wenn Sie nicht den Prototyp einer Funktion auf ein Objekt ändern, die erbt nicht von Object.prototype, alle Instanzen, die mit dieser Funktion als Konstruktor erstellt werden, erben von Object.prototype und sind somit Instanzen von Object.
F.prototype = Object.create(null);
var bar = new F();
bar instanceof F // true
bar instanceof Object // false
Referenz: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
instanceof
Shim (nur theoretische Zwecke, gibt es keine praktische Verwendung für sie):
function instanceOf(object, constructor) {
if (!object) return false;
var object = Object.getPrototypeOf(object);
if (object === constructor.prototype) return true;
return instanceOf(object, constructor);
}
Wo Sie es versucht? – PSL
Google Chrome-Befehlszeile. – KingKongFrog
Es muss nur "wahr" sein. Wo hast du es als "falsch" verstanden? – PSL