Symbol.hasInstance
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
Die statische Dateneigenschaft Symbol.hasInstance
repräsentiert das bekannte Symbol Symbol.hasInstance
. Der instanceof
-Operator ruft dieses Symbol bei seinem rechten Operanden auf, um die Methode zu ermitteln, die verwendet wird, um festzustellen, ob das Konstruktorobjekt ein Objekt als seine Instanz erkennt.
Probieren Sie es aus
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// Expected output: true
Wert
Das bekannte Symbol Symbol.hasInstance
.
Eigenschaften von Symbol.hasInstance | |
---|---|
Schreibbar | nein |
Aufzählbar | nein |
Konfigurierbar | nein |
Beschreibung
Der instanceof
-Operator verwendet den folgenden Algorithmus, um den Rückgabewert von object instanceof constructor
zu berechnen:
- Falls
constructor
eine[Symbol.hasInstance]()
-Methode hat, wird sie mitobject
als erstem Argument aufgerufen, und das Ergebnis, zu einem Boolean gewandelt, wird zurückgegeben. EinTypeError
wird ausgelöst, wennconstructor
kein Objekt ist oder wennconstructor[Symbol.hasInstance]
wedernull
nochundefined
noch eine Funktion ist. - Falls
constructor
keine[Symbol.hasInstance]()
-Methode hat (constructor[Symbol.hasInstance]
istnull
oderundefined
), wird das Ergebnis mit demselben Algorithmus bestimmt wieFunction.prototype[Symbol.hasInstance]()
. EinTypeError
wird ausgelöst, wennconstructor
keine Funktion ist.
Da alle Funktionen standardmäßig von Function.prototype
erben, legt die Methode Function.prototype[Symbol.hasInstance]()
in den meisten Fällen das Verhalten von instanceof
fest, wenn die rechte Seite eine Funktion ist.
Beispiele
Benutzerdefiniertes instanceof-Verhalten
Sie könnten Ihr eigenes instanceof
-Verhalten folgendermaßen implementieren:
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
value(instance) {
return Array.isArray(instance);
},
});
console.log([] instanceof MyArray); // true
Überprüfung der Instanz eines Objekts
Auf die gleiche Weise, wie man prüfen kann, ob ein Objekt eine Instanz einer Klasse ist, indem man das Schlüsselwort instanceof
verwendet, kann man auch Symbol.hasInstance
für solche Überprüfungen nutzen.
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
Spezifikationen
Specification |
---|
ECMAScript® 2025 Language Specification # sec-symbol.hasinstance |
Browser-Kompatibilität
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hasInstance |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support