You need to enable JavaScript to run this app. 是否有方法可以引用JavaScript类所实例化出的全部对象?
优惠活动
大模型
产品
解决方案
定价
更多

是否有方法可以引用JavaScript类所实例化出的全部对象?

JavaScript类实例遍历方案说明

推荐实现方式

不建议修改Object原型实现,会造成全局污染、兼容性问题。更简单高效的方案是在自定义类内维护静态实例集合,实现逻辑如下:

class CustomClass {
  // 静态私有属性存储所有实例引用,避免外部意外修改
  static #instances = [];

  constructor(props) {
    this.props = props;
    // 实例化时自动加入集合
    CustomClass.#instances.push(this);
  }

  // 静态遍历方法
  static forEachInstance(callback) {
    // 遍历前做浅拷贝,避免遍历过程中实例增删导致的执行异常
    [...this.#instances].forEach(callback);
  }

  // 实例销毁方法,避免内存泄漏
  destroy() {
    const idx = CustomClass.#instances.indexOf(this);
    if (idx !== -1) CustomClass.#instances.splice(idx, 1);
  }
}

// 测试用例
const ins1 = new CustomClass({id: 1});
const ins2 = new CustomClass({id: 2});
CustomClass.forEachInstance(ins => console.log(ins.props.id));
// 输出 1、2

原型链方案实现(不推荐生产使用)

如果一定要基于原型链实现,原理是给类原型添加唯一标识,再遍历全局对象筛选符合标识的实例,该方案性能极低(需要遍历全局所有可枚举属性),仅做原理演示:

// 给类原型添加唯一标记
CustomClass.prototype._MY_CUSTOM_CLASS_FLAG = true;

function getAllCustomInstances() {
  const result = [];
  // 用globalThis统一浏览器/Node的全局对象入口
  for (const key in globalThis) {
    if (
      Object.prototype.hasOwnProperty.call(globalThis, key) 
      && globalThis[key]?._MY_CUSTOM_CLASS_FLAG
    ) {
      result.push(globalThis[key]);
    }
  }
  return result;
}

性能优化要点

  • 优先使用静态集合方案,时间复杂度为O(n),n仅为当前类的实例数量,性能远高于原型链遍历方案
  • 不需要使用的实例主动调用destroy方法移除引用,避免集合持有无效实例导致内存泄漏
  • 遍历集合前做浅拷贝,规避遍历过程中实例增删带来的下标偏移问题

环境差异说明

  • 静态集合实现方案在Node、浏览器环境下完全一致,无兼容性差异
  • 原型链遍历方案唯一差异是全局对象:浏览器端全局对象为window,Node <12.0版本全局对象为global,Node 12+和现代浏览器都支持globalThis作为统一全局入口

内容的提问来源于stack exchange,提问作者MRodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 08:15:06