instanceof 通过原型链判断对象与构造函数的继承关系,要求原型链完整连通;ES6 class 自动维护该链,手动继承需正确设置 prototype;跨上下文失效,原始值不适用。

instanceof 在继承体系中能准确反映对象的“血缘关系”,只要原型链完整,它就能识别出实例与父类、子类甚至祖类之间的归属关系。它不看类名或代码结构,只认原型链上的引用是否匹配。
继承链上多层识别有效
ES6 class 继承自动维护原型链:子类实例的 __proto__ 指向子类原型,子类原型的 __proto__ 又指向父类原型。因此一个子类实例能通过 instanceof 同时为子类、父类、Object 返回 true。
- class Animal {}
- class Dog extends Animal {}
- const dog = new Dog()
- dog instanceof Dog → true
- dog instanceof Animal → true
- dog instanceof Object → true
手动继承需确保原型链连通
用构造函数模拟继承时,如果只写 Dog.prototype = new Animal(),但没处理 constructor 或破坏了 __proto__ 链,instanceof 就会失效。关键不是赋值动作本身,而是最终原型链能否逐级到达目标 prototype。
- 错误做法:Dog.prototype = {}(切断了与 Animal.prototype 的连接)
- 正确做法:Dog.prototype = Object.create(Animal.prototype),再补上 Dog.prototype.constructor = Dog
- 也可用 Object.setPrototypeOf(Dog.prototype, Animal.prototype)
跨上下文场景下会失效
iframe、Worker 等独立执行环境各自拥有独立的全局对象,导致 Array、Date 等内置构造函数引用不同。即使两个数组长得一样,iframe 中的 arr instanceof Array 在主窗口里也会返回 false。
- 原因:iframe.contentWindow.Array !== Array,prototype 引用不相等
- 替代方案:对数组用 Array.isArray(),对日期用 Object.prototype.toString.call(obj) === '[object Date]'
原始值和 null 不适用
instanceof 只作用于对象。数字、字符串、布尔等原始值没有原型链,所以 5 instanceof Number 是 false;null 和 undefined 更是连 [[Prototype]] 都没有,直接报错或返回 false。
- 想检测包装对象:new Number(5) instanceof Number → true
- 但日常类型判断应优先用 typeof(基本类型)或专用方法(如 Array.isArray)

















