instanceof 是 javascript 中用于检测对象原型链是否包含某构造函数 prototype 的运算符;仅适用于对象,要求右操作数为具有 prototype 的函数,对原始值或箭头函数等无效,且在跨全局环境时可能失效。

在 JavaScript 中,用构造函数配合 instanceof 检测类型,核心是看对象是否由该构造函数(或其原型链上)创建而来。
构造函数必须是函数,且被 new 调用过
instanceof 判断的是对象的原型链中是否包含构造函数的 prototype。所以只有通过 new 创建的实例,才真正继承了构造函数的原型。
- 正确示例:
function Person(name) {
this.name = name;
}
const p = new Person('Alice');
console.log(p instanceof Person); // true
- 错误示例(未用
new):
const p2 = Person('Bob'); // this 指向全局,没返回对象,p2 是 undefined
console.log(p2 instanceof Person); // TypeError: Right-hand side of 'instanceof' is not an object
instanceof 查的是原型链,不是构造函数名
它不关心变量名或字符串,只检查对象内部的 [[Prototype]] 是否能向上找到 Constructor.prototype。
- 可以跨作用域/跨 iframe(只要原型链连得上);
- 子类实例
instanceof父类也返回true(因为继承了父类 prototype):
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
注意内置类型和箭头函数的限制
内置构造函数(如 Array、Date、RegExp)可以用 instanceof 检测,但要注意:
-
箭头函数不能当构造函数:没有
prototype,不能用new,也不能用于instanceof右侧; -
原始值不行:数字、字符串字面量等不是对象,无法用
instanceof(会直接报错或返回false); -
手动修改原型可能破坏判断:比如
obj.__proto__ = null后,任何instanceof都为false。
替代方案:什么时候别硬用 instanceof
如果只是想区分数据种类,更推荐:
-
Array.isArray()判数组(比arr instanceof Array更可靠,尤其跨 iframe); -
Object.prototype.toString.call(x)获取精确类型标签(如[object Date]); - TypeScript 的类型守卫或运行时类型检查库(如
zod、io-ts)更适合复杂场景。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











