zoukankan      html  css  js  c++  java
  • JS new和instanceof的实现

    function isObject(value) {
      const type = typeof value;
      return value !== null && (type === 'object' || type === 'function');
    }
    
    /**
     * constructor 表示 new 的构造器
     * args 表示传给构造器的参数
     */
    function New(constructor, ...args) {
      // new 的对象不是函数就抛 TypeError
      if (typeof constructor !== 'function') throw new TypeError(`${constructor} is not a constructor`);
    
      // 创建一个原型为构造器的 prototype 的空对象 target
      const target = Object.create(constructor.prototype);
      // 将构造器的 this 指向上一步创建的空对象,并执行,为了给 this 添加实例属性
      const result = constructor.apply(target, args);
    
      // 上一步的返回如果是对象就直接返回,否则返回 target
      return isObject(result) ? result : target;
    }
    function instanceOf(obj, constructor) {
      if (!isObject(constructor)) {
        throw new TypeError(`Right-hand side of 'instanceof' is not an object`);
      } else if (typeof constructor !== 'function') {
        throw new TypeError(`Right-hand side of 'instanceof' is not callable`);
      }
    
      // 主要就这一句
      return constructor.prototype.isPrototypeOf(obj);
    }

    转自:https://juejin.im/post/5e2ff7dce51d4558021a1a4d

  • 相关阅读:
    python imageai 对象检测、对象识别
    flask跨域请求三行代码搞定
    图片压缩-KMeans
    电影天堂
    python 时间操作
    时间HTML
    3D滚动效果
    tensorflow基础
    studio显示Surface: getSlotFromBufferLocked: unknown buffer: 0xa2a58be0
    解决github访问慢和clone慢解决方案
  • 原文地址:https://www.cnblogs.com/qq965921539/p/12539124.html
Copyright © 2011-2022 走看看