Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
1.91k stars 232 forks source link

手写Instanceof详细 #503

Open 1251912798 opened 7 months ago

1251912798 commented 7 months ago
 /* 
    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;
    }
  };
topulikeweb commented 3 months ago
function _Instance(element, target) {
    element = element.__proto__
    target = target.prototype
    while (element !== null) {
        if (target === element) {
            return true
        }
        element = element.__proto__;
    }
    return false
}

console.log(_Instance('111', Number));