instanceof
2023年11月3日大约 2 分钟
instanceof
instanceof 是用于检测一个实例对象是否是某个构造函数的实例
instanceof 的本质是:沿着对象的原型链(proto)向上查找,看是否能找到构造函数的 prototype 属性。
function Person() {}
const p = new Person()
console.log(p instanceof Person) // true
console.log(p instanceof Object) // true,因为 Person.prototype.__proto__ === Object.prototypeinstanceof的行为可以通过Symbol.hasInstance自定义(这里仅仅允许自定义构造函数)
class EvenNumber {
static [Symbol.hasInstance](instance) {
return typeof instance === 'number' && instance % 2 === 0
}
}
console.log(2 instanceof EvenNumber) // true
console.log(3 instanceof EvenNumber) // false
// 被忽略
Array[Symbol.hasInstance] = ()=> false
console.log([] instanceof Array)手写 instanceof 更容易理解
function myInstanceof(obj, constructor) {
if (typeof constructor !== 'function') {
throw new Error('type error constructor')
}
const hasInstanceofMethod = constructor[Symbol.hasInstance]
if (typeof hasInstanceofMethod === 'function') {
return !!hasInstanceofMethod.call(constructor, obj)
}
if (typeof obj !== 'object' || typeof obj === null) return false
let _proto_ = Object.getPrototypeOf(obj)
const prototype = Object.getPrototypeOf(constructor)
while (_proto_ != null) {
if (_proto_ === prototype) return true
_proto_ = Object.getPrototypeOf(_proto_)
}
return falsea
}
背景
「instanceof」属于对象模型基础主题,理解深度直接影响复杂调试与框架源码阅读效率。
核心原理
对象访问基于原型链查找,实例创建依赖构造流程与 this 绑定规则。
实现方式 / 示例
建议配套给出“标准场景 + 反例场景”,验证原型遮蔽、返回对象、跨上下文 instanceof 的差异。
常见问题
- prototype 与 proto 概念混用。
- 忽视 constructor 返回值规则。
- 在多运行时上下文中误用实例判断。
最佳实践
在知识文档中显式标注边界行为与替代判断方法,避免经验化误导。
总结
围绕「instanceof」的掌握程度决定了你对 JS 对象行为的可预测性。
