You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何统计工厂函数创建的对象数量并为实例设置带序号名称

实现方案

推荐使用闭包保存私有计数器的方案,既不会污染全局作用域,也能避免计数器被外部意外篡改,具体代码如下:

const itemFactory = (() => {
  // 闭包内私有计数器,仅工厂函数内部可访问
  let createCount = 0

  return () => {
    const itemName = `item${createCount}`
    const firstMethod = () => {
      // 原有业务逻辑保持不变
    }

    // 每次创建实例后计数器自增
    createCount++
    // 可选:挂载静态方法获取总创建数量
    itemFactory.getTotalCount = () => createCount

    return { itemName, firstMethod }
  }
})()

使用示例

const a = itemFactory()
const b = itemFactory()
const c = itemFactory()

console.log(a.itemName) // 输出 item0
console.log(b.itemName) // 输出 item1
console.log(c.itemName) // 输出 item2
console.log(itemFactory.getTotalCount()) // 输出总创建数量 3

如果你不需要额外封装,可以选择更简单的计数器挂载方案,缺点是计数器对外暴露可被修改:

const itemFactory = () => {
  // 首次调用时初始化计数器
  itemFactory.createCount = itemFactory.createCount ?? 0
  const itemName = `item${itemFactory.createCount}`
  const firstMethod = () => {
    // 原有业务逻辑
  }

  itemFactory.createCount++
  return { itemName, firstMethod }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:15:02