instanceof
2025年7月16日小于 1 分钟
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.prototype
instanceof
的行为可以通过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
}
