instanceof检测数据类型原理

// instanceof:检测原理
//   + 构造函数 Symbol.hasInstance 属性方法
//   + 检测构造函数的prototype是否出现在实例的__proto__上
//   + 不能检测基本数据类型,检测的实例必须都是对象
//   + ...
 
function instance_of(example,classFun){
  //参数初始化,classFun 必须是一个函数
  if(typeof classFun !== 'function') throw new TypeError('===========');
  if(example == null) return false;
  // 支持Symbol的并且拥有Symbol.hasInstance,以这个处理
  if(typeof Symbol  !== 'undefined'){
           let hasInstance = classFun[Symbol.hasInstance];
    if(tyleof hasInstance === 'function'){
      return hasInstance.call(classFun , example)
    }
        }
  //如果不支持Symbol,则检测原型链是是否存在
  let prototype = classFun.protype;
       let proto = Object.getPrototypeOf(example);  //获取example 的原型
    if(!prototype) return false  //对于没有prototype 的函数 直接返回false,如箭头函数
  while(true){
    if(proto == null ) return false;
    if(proto == prototype ) return true;
    proto = Object.getPrototypeOf(proto);
        }
}
例如:
let res = instance_of([12, 23], Array);
console.log(res); //=>true  

res = instance_of([12, 23], Object);
console.log(res); //=>true  

res = instance_of([12, 23], RegExp);
console.log(res); //=>false  
posted @ 2020-11-23 15:21  box的紫色边框  阅读(285)  评论(0)    收藏  举报