Spec-Zone.ru › JavaScript

TypeError: invalid 'instanceof' operand 'x'

Исключение JavaScript "invalid 'instanceof' operand" возникает, когда правый операнд оператора instanceof используется не с объектом-конструктором, т.е. объектом, который имеет свойство prototype и является вызываемым.

Сообщение

TypeError: Right-hand side of 'instanceof' is not an object (V8-based)
TypeError: invalid 'instanceof' operand "x" (Firefox)
TypeError: Right hand side of instanceof is not an object (Safari)

TypeError: Right-hand side of 'instanceof' is not callable (V8-based)
TypeError: x is not a function (Firefox)
TypeError: x is not a function. (evaluating 'x instanceof y') (Safari)

TypeError: Function has non-object prototype 'undefined' in instanceof check (V8-based)
TypeError: 'prototype' property of x is not an object (Firefox)
TypeError: instanceof called on an object with an invalid prototype property. (Safari)

Тип ошибки

TypeError

Что пошло не так?

Оператор instanceof ожидает, что правый операнд будет объектом-конструктором, то есть объектом, который имеет свойство prototype и является вызываемым. Он также может быть объектом с методом Symbol.hasInstance. Эта ошибка может возникнуть, если:

  • Правый операнд не является объектом.
  • Правый операнд не является вызываемым и не имеет метода Symbol.hasInstance.
  • Правый операнд является вызываемым, но его свойство prototype не является объектом. (Например, стрелочные функции не имеют свойства prototype.)

Примеры

instanceof против typeof

"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
42 instanceof 0; // TypeError: invalid 'instanceof' operand 0

function Foo() {}
const f = Foo(); // Foo() is called and returns undefined
const x = new Foo();

x instanceof f; // TypeError: invalid 'instanceof' operand f
x instanceof x; // TypeError: x is not a function

Чтобы исправить эти ошибки, вам нужно либо заменить оператор instanceof на оператор typeof, либо убедиться, что вы используете имя функции, а не результат её выполнения.

typeof "test" === "string"; // true
typeof 42 === "number"; // true

function Foo() {}
const f = Foo; // Do not call Foo.
const x = new Foo();

x instanceof f; // true
x instanceof Foo; // true

Смотрите также

  • instanceof
  • typeof

© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API