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

  • 相关阅读:
    git代码回退
    7 用两个栈实现队列
    《Java并发编程实战》学习笔记
    226. Invert Binary Tree
    Interface与abstract类的区别
    Override和Overload的区别
    Java面向对象的三个特征与含义
    String、StringBuffer与StringBuilder的区别
    Hashcode的作用
    Object有哪些公用方法
  • 原文地址:https://www.cnblogs.com/qq965921539/p/12539124.html
Copyright © 2011-2022 走看看