instanceof
是 JavaScript 中的一个运算符,用于检查一个对象是否是某个类的实例,或者是否在其原型链中存在该类的原型。
object instanceof constructor
object
:要检查的对象constructor
:要检查的构造函数/类class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true (因为 Dog 继承自 Animal)
console.log(dog instanceof Object); // true (所有对象都继承自 Object)
instanceof
检查构造函数的 prototype
属性是否出现在对象的原型链中的任何位置。
function Car(make) {
this.make = make;
}
const myCar = new Car('Toyota');
console.log(myCar instanceof Car); // true
console.log(myCar instanceof Object); // true
原始值:原始类型(如数字、字符串、布尔值)不是任何对象的实例
console.log('hello' instanceof String); // false
console.log(new String('hello') instanceof String); // true
跨窗口/框架:不同窗口或框架中的对象会有不同的构造函数
// 如果在iframe中检查父窗口的对象
parentObj instanceof parent.Array // 正确方式
Symbol.hasInstance:可以自定义 instanceof
的行为
class MyClass {
static [Symbol.hasInstance](instance) {
return typeof instance === 'string';
}
}
console.log('hello' instanceof MyClass); // true
typeof
返回一个表示数据类型的字符串instanceof
检查对象与构造函数之间的关系console.log(typeof []); // "object"
console.log([] instanceof Array); // true
prototype
,之前创建的对象可能不再被认为是其实例Object.create(null)
),instanceof
总是返回 falseinstanceof
也可以用于检查内置对象如 Array
, Map
, Set
等在某些情况下,可以使用:
Object.prototype.isPrototypeOf()
constructor
属性(不太可靠,因为可以被修改)Array.isArray()
等特定类型检查方法instanceof
是 JavaScript 中类型检查的强大工具,特别是在处理自定义类和继承层次结构时。