Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写Instanceof详细 #503

Open
1251912798 opened this issue Dec 6, 2023 · 1 comment
Open

手写Instanceof详细 #503

1251912798 opened this issue Dec 6, 2023 · 1 comment

Comments

@1251912798
Copy link

 /* 
    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;
    }
  };
@1251912798 1251912798 changed the title myInstancof 手写Instancof Dec 6, 2023
@1251912798 1251912798 changed the title 手写Instancof 手写Instancof详细 Dec 6, 2023
@1251912798 1251912798 changed the title 手写Instancof详细 手写Instanceof详细 Dec 7, 2023
@topulikeweb
Copy link

function _Instanceof (element, target) {
  element = element.__proto__
  target = target.prototype
  while (element != null) {
    element = element.__proto__
    if (element === target) {
      return true
    }
  }
  return false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants