Skip to content

手写Instanceof详细 #503

@1251912798

Description

@1251912798
 /* 
    instanceof 实现思路
    es6给所有的构造函数添加了[Symbol.hasInstance]它的返回值就是instanceof的返回值
    而有一些低版本浏览器不兼容es6的语法无法识别Symbol,那么它就按照原型链进行查找
  */
  var myInstance_of = function myInstance_of(obj, ctor) {
    if (typeof ctor === null && !/^(object|function)$/.test(typeof ctor))
      throw new TypeError(
        "Right-hand side of 'instanceof' is not an object"
      );

    // 判断传入的是否是一个函数
    if (typeof ctor !== "function")
      throw new TypeError(
        "Right-hand side of  instanceof  is not callable"
      );

    // 判断这个函数是否存在原型链
    if (!ctor.prototype)
      throw new TypeError(
        "Function has non-object prototype 'undefined' in instanceof check"
      );

    // 不支持基本数据类型的检测
    if (typeof obj === null && !/^(object|function)$/.test(typeof obj))
      return false;

    // 判断浏览器是否能识别Symbol
    if (typeof Symbol !== "undefined") {
      // es6给所有的构造函数都加上了[Symbol.haInstance]
      const hasInstance = ctor[Symbol.hasInstance];
      if (typeof ctor === "function") {
        return hasInstance.call(ctor, obj);
      }
      // 从原型链查找进行判断
      var protot = Object.getPrototypeOf(obj);
      while (protot) {
        if (protot === ctor.prototype) return true;
        protot = protot.getPrototypeOf(protot);
      }
      return false;
    }
  };

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions