当前位置:首页 > JavaScript

js instanceof实现

2026-03-15 11:09:24JavaScript

实现 instanceof 的手动版本

JavaScript 的 instanceof 运算符用于检测构造函数的 prototype 属性是否出现在对象的原型链上。以下是手动实现 instanceof 的方法:

function myInstanceof(obj, constructor) {
  // 获取对象的原型
  let proto = Object.getPrototypeOf(obj);
  // 获取构造函数的原型
  const prototype = constructor.prototype;

  // 遍历原型链
  while (proto !== null) {
    if (proto === prototype) {
      return true;
    }
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

使用示例

function Person() {}
const p = new Person();

console.log(myInstanceof(p, Person)); // true
console.log(myInstanceof(p, Object)); // true
console.log(myInstanceof([], Array)); // true
console.log(myInstanceof([], Object)); // true
console.log(myInstanceof([], Function)); // false

实现原理说明

手动实现 instanceof 的关键在于遍历对象的原型链。通过 Object.getPrototypeOf 获取对象的原型,并与构造函数的 prototype 属性比较。如果找到匹配的原型,返回 true;如果遍历到原型链顶端(null)仍未找到匹配,返回 false

边界情况处理

  • 如果 obj 不是对象(如基本类型 nullundefinednumber 等),直接返回 false
  • 如果 constructor 不是函数(如基本类型或非构造函数对象),抛出 TypeError
function myInstanceof(obj, constructor) {
  if (typeof constructor !== 'function') {
    throw new TypeError('Right-hand side of instanceof is not callable');
  }
  if (obj === null || typeof obj !== 'object') {
    return false;
  }
  let proto = Object.getPrototypeOf(obj);
  const prototype = constructor.prototype;
  while (proto !== null) {
    if (proto === prototype) {
      return true;
    }
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

与原生 instanceof 的差异

原生 instanceof 还支持检查 Symbol.hasInstance 方法(如果构造函数定义了该方法)。手动实现通常不包含这一特性,但可以通过以下方式扩展:

js instanceof实现

function myInstanceof(obj, constructor) {
  if (typeof constructor !== 'function') {
    throw new TypeError('Right-hand side of instanceof is not callable');
  }
  if (typeof constructor[Symbol.hasInstance] === 'function') {
    return constructor[Symbol.hasInstance](obj);
  }
  if (obj === null || typeof obj !== 'object') {
    return false;
  }
  let proto = Object.getPrototypeOf(obj);
  const prototype = constructor.prototype;
  while (proto !== null) {
    if (proto === prototype) {
      return true;
    }
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

标签: jsinstanceof
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…