Dieser Inhalt wurde automatisch aus dem Englischen übersetzt, und kann Fehler enthalten.Erfahre mehr über dieses Experiment.
instanceof
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since Juli 2015.
Derinstanceof Operator testet, ob dieprototype Eigenschaft eines Konstruktors irgendwo in der Prototypenkette eines Objekts erscheint. Der Rückgabewert ist ein boolescher Wert. Sein Verhalten kann mitSymbol.hasInstance angepasst werden.
In diesem Artikel
Probieren Sie es aus
function Car(make, model, year) { this.make = make; this.model = model; this.year = year;}const auto = new Car("Honda", "Accord", 1998);console.log(auto instanceof Car);// Expected output: trueconsole.log(auto instanceof Object);// Expected output: trueSyntax
object instanceof constructorParameter
objectDas zu testende Objekt.
constructorKonstruktor, gegen den getestet werden soll.
Ausnahmen
TypeErrorWird ausgelöst, wenn
constructorkein Objekt ist. Wennconstructorkeine[Symbol.hasInstance]()Methode hat, muss es auch eine Funktion sein.
Beschreibung
Derinstanceof Operator überprüft das Vorhandensein vonconstructor.prototype in der Prototypenkette vonobject. Dies bedeutet normalerweise (abernicht immer), dassobject mitconstructor konstruiert wurde.
// defining constructorsfunction C() {}function D() {}const o = new C();// true, because: Object.getPrototypeOf(o) === C.prototypeo instanceof C;// false, because D.prototype is nowhere in o's prototype chaino instanceof D;o instanceof Object; // true, because:C.prototype instanceof Object; // true// Re-assign `constructor.prototype`: you should// rarely do this in practice.C.prototype = {};const o2 = new C();o2 instanceof C; // true// false, because C.prototype is nowhere in// o's prototype chain anymoreo instanceof C;D.prototype = new C(); // add C to [[Prototype]] linkage of Dconst o3 = new D();o3 instanceof D; // trueo3 instanceof C; // true since C.prototype is now in o3's prototype chainBeachten Sie, dass sich der Wert einesinstanceof Tests ändern kann, wennconstructor.prototype neu zugewiesen wird, nachdem das Objekt erstellt wurde (was normalerweise nicht empfohlen wird). Er kann auch geändert werden, indem der Prototyp vonobject mitObject.setPrototypeOf geändert wird.
Klassen verhalten sich auf die gleiche Weise, da Klassen auch dieprototype Eigenschaft haben.
class A {}class B extends A {}const o1 = new A();// true, because Object.getPrototypeOf(o1) === A.prototypeo1 instanceof A;// false, because B.prototype is nowhere in o1's prototype chaino1 instanceof B;const o2 = new B();// true, because Object.getPrototypeOf(Object.getPrototypeOf(o2)) === A.prototypeo2 instanceof A;// true, because Object.getPrototypeOf(o2) === B.prototypeo2 instanceof B;Fürgebundene Funktionen suchtinstanceof nach derprototype Eigenschaft in der Zielfunktion, da gebundene Funktionen keinprototype haben.
class Base {}const BoundBase = Base.bind(null, 1, 2);console.log(new Base() instanceof BoundBase); // trueinstanceof und Symbol.hasInstance
Wennconstructor eineSymbol.hasInstance Methode hat, wird die Methode vorrangig aufgerufen, mitobject als einzigem Argument undconstructor alsthis.
// This class allows plain objects to be disguised as this class's instance,// as long as the object has a particular flag as its property.class Forgeable { static isInstanceFlag = Symbol("isInstanceFlag"); static [Symbol.hasInstance](obj) { return Forgeable.isInstanceFlag in obj; }}const obj = { [Forgeable.isInstanceFlag]: true };console.log(obj instanceof Forgeable); // trueDa alle Funktionen standardmäßig vonFunction.prototype erben, legt dieFunction.prototype[Symbol.hasInstance]() Methode die meiste Zeit das Verhalten voninstanceof fest, wenn die rechte Seite eine Funktion ist. Siehe dieSymbol.hasInstance Seite für den genauen Algorithmus voninstanceof.
instanceof und mehrere Realms
JavaScript Ausführungsumgebungen (Fenster, Frames usw.) befinden sich jeweils in ihrem eigenenRealm. Dies bedeutet, dass sie unterschiedliche Built-ins haben (unterschiedliches globales Objekt, unterschiedliche Konstruktoren usw.). Dies kann zu unerwarteten Ergebnissen führen. Zum Beispiel wird[] instanceof window.frames[0].Arrayfalse zurückgeben, daArray.prototype !== window.frames[0].Array.prototype und Arrays im aktuellen Realm vom früheren erben.
Dies mag zuerst keinen Sinn ergeben, aber für Skripte, die mit mehreren Frames oder Fenstern arbeiten und Objekte über Funktionen von einem Kontext in einen anderen übergeben, wird dies ein gültiges und bedeutendes Problem sein. Beispielsweise können Sie sicher überprüfen, ob ein gegebenes Objekt tatsächlich ein Array ist, indem SieArray.isArray() verwenden, unabhängig davon, aus welchem Realm es stammt.
Um beispielsweise zu überprüfen, ob einNode einSVGElement in einem anderen Kontext ist, können SiemyNode instanceof myNode.ownerDocument.defaultView.SVGElement verwenden.
Beispiele
>Verwenden von instanceof mit String
Das folgende Beispiel zeigt das Verhalten voninstanceof mitString Objekten.
const literalString = "This is a literal string";const stringObject = new String("String created with constructor");literalString instanceof String; // false, string primitive is not a StringstringObject instanceof String; // trueliteralString instanceof Object; // false, string primitive is not an ObjectstringObject instanceof Object; // truestringObject instanceof Date; // falseVerwenden von instanceof mit Map
Das folgende Beispiel zeigt das Verhalten voninstanceof mitMap Objekten.
const myMap = new Map();myMap instanceof Map; // truemyMap instanceof Object; // truemyMap instanceof String; // falseObjekte, die mit Object.create() erstellt wurden
Das folgende Beispiel zeigt das Verhalten voninstanceof mit Objekten, die mitObject.create() erstellt wurden.
function Shape() {}function Rectangle() { Shape.call(this); // call super constructor.}Rectangle.prototype = Object.create(Shape.prototype);Rectangle.prototype.constructor = Rectangle;const rect = new Rectangle();rect instanceof Object; // truerect instanceof Shape; // truerect instanceof Rectangle; // truerect instanceof String; // falseconst literalObject = {};const nullObject = Object.create(null);nullObject.name = "My object";literalObject instanceof Object; // true, every object literal has Object.prototype as prototype({}) instanceof Object; // true, same case as abovenullObject instanceof Object; // false, prototype is end of prototype chain (null)Demonstrieren, dass myCar vom Typ Car und vom Typ Object ist
Der folgende Code erstellt einen ObjekttypCar und eine Instanz dieses Objekttyps,myCar. Derinstanceof Operator zeigt, dass dasmyCar Objekt vom TypCar und vom TypObject ist.
function Car(make, model, year) { this.make = make; this.model = model; this.year = year;}const myCar = new Car("Honda", "Accord", 1998);const a = myCar instanceof Car; // returns trueconst b = myCar instanceof Object; // returns trueKein instanceof
Um zu testen, ob ein Objektkeininstanceof eines spezifischen Konstruktors ist, können Sie folgendes tun:
if (!(myCar instanceof Car)) { // Do something, like: // myCar = new Car(myCar)}Dies ist wirklich anders als:
if (!myCar instanceof Car) { // unreachable code}Dies wird immerfalse sein. (!myCar wird vorinstanceof ausgewertet, daher versuchen Sie immer, zu wissen, ob ein boolescher Wert eine Instanz vonCar ist).
Das Verhalten von instanceof überschreiben
Ein häufiger Trugschluss bei der Verwendung voninstanceof ist der Glaube, dass, wennx instanceof C,x mitC als Konstruktor erstellt wurde. Das ist nicht wahr, dennx könnte direkt mitC.prototype als seinem Prototyp zugewiesen worden sein. In diesem Fall würde das Lesen vonprivaten Feldern vonC ausx immer noch fehlschlagen:
class C { #value = "foo"; static getValue(x) { return x.#value; }}const x = { __proto__: C.prototype };if (x instanceof C) { console.log(C.getValue(x)); // TypeError: Cannot read private member #value from an object whose class did not declare it}Um dies zu vermeiden, können Sie das Verhalten voninstanceof überschreiben, indem Sie eineSymbol.hasInstance Methode zuC hinzufügen, sodass es eine markenbasierte Überprüfung mitin durchführt:
class C { #value = "foo"; static [Symbol.hasInstance](x) { return #value in x; } static getValue(x) { return x.#value; }}const x = { __proto__: C.prototype };if (x instanceof C) { // Doesn't run, because x is not a C console.log(C.getValue(x));}Beachten Sie, dass Sie dieses Verhalten möglicherweise auf die aktuelle Klasse beschränken möchten; andernfalls könnte es zu falschen positiven Ergebnissen für Unterklassen führen:
class D extends C {}console.log(new C() instanceof D); // true; because D inherits [Symbol.hasInstance] from CSie könnten dies tun, indem Sie prüfen, obthis der aktuelle Konstruktor ist:
class C { #value = "foo"; static [Symbol.hasInstance](x) { return this === C && #value in x; }}class D extends C {}console.log(new C() instanceof D); // falseconsole.log(new C() instanceof C); // trueconsole.log({ __proto__: C.prototype } instanceof C); // falseSpezifikationen
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-relational-operators> |