怎样判断数据是一个数组?自定义一个instanceof

60 阅读1分钟

let arr = [1,2,3]

  1. arr instanceof Array ==> boolean 判断一个对象是否为某个类(构造函数)的实例
  2. Array.isArray(arr) ==> boolean
  3. arr.constructor === Array
  4. Object.getPropertyOf(arr) === Array.prototype
function myInstanceOf(obj, constructor) {
  // 检查参数是否为函数
  if (typeof constructor !== 'function') {
    throw new Error('Right-hand side of \'instanceof\' is not callable');
  }

  // 检查参数是否为对象
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
    return false;
  }

  let prototype = Object.getPrototypeOf(obj); // 获取对象的原型

  while (prototype !== null) {
    if (prototype === constructor.prototype) {
      return true;
    }
    prototype = Object.getPrototypeOf(prototype); // 沿原型链向上查找
  }

  return false; // 如果没有找到匹配的原型,则返回 false
}