zoukankan      html  css  js  c++  java
  • 561 手写instanceof

    // example:要检测的实例 
    // classFunc:要检测的类
    function instance_of(example, classFunc) {
      // TZH: 判断是否是基本类型要反向判断,即判断是否object(null特殊处理)和function。
      // 因为纵观es发展历史,基本类型还可能会继续增加,但是引用类型应该会一直只有刚才说那两个,因为es进化时会考虑网络兼容性。
      // 判断是否function、object可以保证随着es进化继续向后兼容。
      // 下面2行是我增加的代码
      if (example === null) return false
      if (!/^object|function$/.test(typeof example)) return false
    
      // 找当前实例的原型,相当于example.__proto
      let proto = Object.getPrototypeOf(example);
      let classPrototype = classFunc.prototype;
      while (true) {
        // 到了Object.prototype.__proto__
        if (proto === null) return false;
        // 在当前实例的原型链上找到了当前类
        if (proto === classPrototype) return true;
        // 继续找上一级的原型 【不是找classPrototype的上一级原型链。】
        proto = Object.getPrototypeOf(proto);
      }
    }
    
    // Function.prototype : Symbol.hasInstance
    console.log([] instanceof Array);
    // 浏览器内部其实是基于Symbol.hasInstance检测的
    console.log(Array[Symbol.hasInstance]([]));
    
    let res = instance_of([12, 23], Array);
    console.log(res); // true
    
    let res2 = instance_of({}, Object)
    console.log(res2) // true
    
    let res3 = instance_of(function () { }, Object)
    console.log(res3) // true
    
    let res4 = instance_of({}, Array)
    console.log(res4) // false
    
    let res5 = instance_of(function () { }, Array)
    console.log(res5) // false
    
    let res6 = instance_of(11, Number)
    console.log(res6) // false
    
  • 相关阅读:
    NCD 2019 M. NCD Salary
    NCD 2019 H. Mr. Hamra and his quantum particles
    Codeforces Testing Round #16 C.Skier
    序列自动机(数组)
    Codeforces #640 div4 F~G (构造二连弹)
    NCD 2019 C. Hasan and his lazy students
    欧拉定理,费马小定理
    微信开发
    异常后显示错误页面
    js窗体间传值
  • 原文地址:https://www.cnblogs.com/jianjie/p/13867628.html
Copyright © 2011-2022 走看看