JS中单例的销毁问题

目前遵循单一职责的原则, 单例的管理函数和单例的创建函数是分开的, 如下:

function handleSingleton (createFn){
  // createFn是单例的创建函数(例如创建一个div元素等)
  let created = null
  return function (...rest) {
    return created || (created = createFn.apply(this, rest))
  }
}

但这样有个问题: 单例创建后无法有效地销毁. 为了解决这个问题, 增加了一个destroyFn函数用于销毁闭包内的created变量, 并根据传入的type来决定是调用createFn来创建单例, 还是调用destroyFn来销毁单例:

function handleSingleton (createFn, destroyFn){
  let created = null
  // 判断传入的type
  return function (type, ...rest) {
    if (type === 'create') {
      return created || (created = createFn.apply(this, rest))
    } else if (type === 'destroy') {
      destroyFn.call(this, created, ...rest)
      created = null
    } else {
      throw new Error('\'type\' can either be \'create\' or \'destroy!\'')
    }
  }
}

有没有更好的办法呢?

阅读 5.2k
1 个回答

在handleSingleton的返回函数上添加一个销毁函数,用于销毁自己

function handleSingleton (createFn){
  // createFn是单例的创建函数(例如创建一个div元素等)
  let created = null
  let ret =  function (...rest) {
    return created || (created = createFn.apply(this, rest))
  }
  ret.distroy = function(distroyFn){
    distroyFn && distroyFn()
    created = null
  }
  return ret
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题