js--instanceof实现

js--instanceof实现


  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
    在这里插入图片描述

code


function _instanceof(left, right) {

    //如果是基本数据类型,返回false  
    // typeof null 是object ,要处理这种情况 
    if (typeof (left) !== "object" || left == undefined) {
        return false;
    }

    // 获取原型对象
    // 举个例子:Object.getPrototypeOf([])===[].__proto__  true
    let prototype = Object.getPrototypeOf(left);

    while (true) {

        //一直按着原型链查找  找到顶层还找不到,返回null

        if (prototype === null) {
            return false;
        }

        // 如果left right 原型对象一样 返回true
        if (prototype == right.prototype) {
            return true;
        }

        // 不满足条件的  继续查找
        //一直到   Object.getPrototypeOf(Object.getPrototypeOf({})) null
        prototype = Object.getPrototypeOf(prototype);


    }

}

pic

在这里插入图片描述

发布了396 篇原创文章 · 获赞 786 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_42813491/article/details/102929771