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
    
  • 相关阅读:
    证书介绍
    Hadoop生态上几个技术的关系与区别:hive、pig、hbase 关系与区别
    Hive安装与配置详解
    技术学习内容
    死锁,更新锁,共享锁,排它锁,意向锁,乐观锁,悲观锁等名词解释及案例详解
    死锁语句
    SQL Server 锁表、查询被锁表、解锁相关语句
    Psi Probe 安装及使用说明
    PowerDesigner使用教程
    Python -面向对象(一 基本概念)
  • 原文地址:https://www.cnblogs.com/jianjie/p/13867628.html
Copyright © 2011-2022 走看看