TypeError: invalid 'instanceof' operand 'x'

JavaScript 異常 "invalid 'instanceof' operand"(無效的 instanceof 運算元)發生在 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

js
"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 運算子,或者確保你使用的是函式名稱,而不是其求值結果。

js
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

另見