Baseline Widely available
Die Symbol.hasInstance
statische Dateneigenschaft repräsentiert das wohlbekannte Symbol Symbol.hasInstance
. Der instanceof
Operator sucht dieses Symbol auf seinem rechten Operanden, um die Methode zu ermitteln, die verwendet wird, um festzustellen, ob das Konstruktorobjekt ein Objekt als seine Instanz erkennt.
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// Expected output: true
Wert
Das wohlbekannte Symbol Symbol.hasInstance
.
Der instanceof
Operator verwendet den folgenden Algorithmus, um den Rückgabewert von object instanceof constructor
zu berechnen:
constructor
eine [Symbol.hasInstance]()
Methode hat, wird diese mit object
als erstem Argument aufgerufen und das Ergebnis zurückgegeben, zu einem Boolean umgewandelt. Ein TypeError
wird ausgelöst, wenn constructor
kein Objekt ist oder wenn constructor[Symbol.hasInstance]
weder null
, undefined
noch eine Funktion ist.constructor
keine [Symbol.hasInstance]()
Methode hat (constructor[Symbol.hasInstance]
ist null
oder undefined
), wird das Ergebnis unter Verwendung des gleichen Algorithmus wie bei Function.prototype[Symbol.hasInstance]()
bestimmt. Ein TypeError
wird ausgelöst, wenn constructor
keine Funktion ist.Da alle Funktionen standardmäÃig von Function.prototype
erben, legt in den meisten Fällen die Methode Function.prototype[Symbol.hasInstance]()
das Verhalten von instanceof
fest, wenn die rechte Seite eine Funktion ist.
Sie könnten Ihr benutzerdefiniertes instanceof
Verhalten wie folgt 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üfen der Instanz eines Objekts
Genauso wie Sie überprüfen können, ob ein Objekt eine Instanz einer Klasse mit dem Schlüsselwort instanceof
ist, können wir auch Symbol.hasInstance
für solche Ãberprüfungen verwenden.
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
Spezifikationen Browser-Kompatibilität Siehe auch
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4