手写instanceOf实现

339 阅读1分钟

1、instanceOf的基本作用: 判断实例对象类型是否属于某个类型。 语法形式: 左 instance 右 其中左侧为需要判断的对象,右侧为函数类型 其内部机制是通过判断对象的原型链是否能找到函数类型的prototype。

手写实现 输入:参数1:进行判别的对象 参数2:比较的函数类型 输出:true/false

        function myInstanceof(left,right) {
        	//参数为非基本类型判别
            const baseType = ['string','symbol','undefined','number','boolean']; 
            if (baseType.includes(typeof(left))){
                return false
            }
            //对象类型参数判别
            let prototype = right.prototype //获取类型的原型
            left = left._proto_;//获得实例的原型
            while(true){
                //已经找到原型链的最顶端指向null,说明没找到
                if(left === null){
                    return false
                } 
                if (left === prototype){ //严格相等
                    return true
                }
                left = left._proto_; //没找到,继续向上一层原型链查找
            }
        }