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

  • 相关阅读:
    Google Authentication 机制原理
    ldap日志
    ldap + kerberos 整合
    kerberos
    U盘格式化后的恢复
    初始化脚本(Os_Init_Optimization.sh)
    拿到新机器,进行初始化和部署Nginx的过程
    python 列表生成式
    python 装饰器
    简单总结无线CPE、无线AP、无线网桥的不同之处【转】
  • 原文地址:https://www.cnblogs.com/qq965921539/p/12539124.html
Copyright © 2011-2022 走看看