×

前端开发:解析TypeError: invalid 'instanceof' operand 'x' 报错应用

作者:andy0012021.04.21来源:Web前端之家浏览:7052评论:0
关键词:js

我们在前端开发过程中,会遇到TypeError: invalid 'instanceof' operand 'x' 这样的报错。我们查看console的信息,如下:

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)

分析后,发现:

哪里出错了?

instanceof 操作符 希望右边的操作数为一个构造对象,即一个有 prototype 属性且可以调用的对象。

例子

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

function Foo() {}
var f = Foo();        // Foo() is called and returns undefined
var 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() {}
var f = Foo;               // Do not call Foo.
var x = new Foo();

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

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/jserror20210421a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: