value instanceof Constructor

不啰嗦,一句话阐述instanceof操作符的原理:

value的原型链中是否包含Constructor的原型对象

function myInstanceof(instance, constructor) {
    const currentPrototype = Object.getPrototypeOf(instance)

    if (currentPrototype === null) {
        return false
    }

    if (currentPrototype.constructor === constructor) {
        return true
    }

    return myInstanceof(currentPrototype, constructor)
}

console.log(myInstanceof([], Array)) // true
console.log(myInstanceof([], Object)) // true
console.log(myInstanceof([], Date)) // false
console.log(myInstanceof(() => { }, Function)) // true
console.log(myInstanceof(() => { }, Object)) // true
console.log(myInstanceof(() => { }, Array)) // false
console.log(myInstanceof({}, Object)) // true
console.log(myInstanceof({}, Function)) // false
console.log(myInstanceof({}, Array)) // false

欢迎评论,欢迎纠错,我们一起成长!
xyzh.work@foxmail.com


周翔宇
1 声望0 粉丝