instanceof原理是什么,请写代码表示

instanceof 的原理

例如 f instanceof Foo

顺着 f.__proto__ 向上查找(原型链)

看能否找到 Foo.prototype

代码

/**
 * @description 手写 instanceof
 */

/**
 * 自定义 instanceof
 * @param instance instance
 * @param origin class or function
 */
export function myInstanceof(instance: any, origin: any): boolean {
    if (instance == null) return false // null undefined

    const type = typeof instance
    if (type !== 'object' && type !== 'function') {
        // 值类型
        return false
    }

    let tempInstance = instance // 为了防止修改 instance
    while (tempInstance) {
        if (tempInstance.__proto__ === origin.prototype) {
            return true // 配上了
        }
        // 未匹配
        tempInstance = tempInstance.__proto__ // 顺着原型链࿰

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124973095