TypeError: invalid 'instanceof' operand 'x'
Message
TypeError: invalid 'instanceof' operand "x" (Firefox) TypeError: "x" is not a function (Firefox) TypeError: Right-hand side of 'instanceof' is not an object (Chrome) TypeError: Right-hand side of 'instanceof' is not callable (Chrome)
Type d'erreur
Quel est le problème ?
L'opérateur instanceof
attend un opérande droit qui soit un objet constructeur, c'est-à-dire un objet possédant une propriété prototype
et qui puisse être appelé.
Exemples
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
42 instanceof 0; // TypeError: invalid 'instanceof' operand 0
function Toto() {}
var f = Toto(); // Toto() est appelé et renvoie undefined
var x = new Toto();
x instanceof f; // TypeError: invalid 'instanceof' operand f
x instanceof x; // TypeError: x is not a function
Pour corriger ces erreurs, il faut remplacer l'opérateur instanceof
avec l'opérateur typeof
ou s'assurer que l'opérande droit est la fonction et non le résultat de son évaluation.
typeof "test" == "string"; // true
typeof 42 == "number" // true
function Toto() {}
var f = Toto; // On n'appelle pas Toto.
var x = new Toto();
x instanceof f; // true
x instanceof Toto; // true
Voir aussi
- L'opérateur
instanceof
- L'opérateur
typeof