优秀的编程知识分享平台

网站首页 > 技术文章 正文

来,看看这段代码有啥问题?(代码1a)

nanyue 2024-08-10 18:37:57 技术文章 12 ℃

在日常的项目开发中我们经常会抽离封装一些工具方法,以便多模块复用,这是好的习惯,但,如果你封装的方法 有 bug,又被多模块使用了,那.....,结果你晓得的。

既然是复用,就必须考虑多场景,多数据类型,又要求稳定,简单,好用。下面这段代码的功能是简单封装了localStorage常用的几个方法,但隐藏着bug,你能发现不?

// storage
const storage = {
  set(key,val){
    if(!window.localStorage){
      return
    }
    localStorage.setItem(key,JSON.stringify(val))
  },
  get(key){
    if(!window.localStorage){
      return
    }
    let _data = JSON.parse(localStorage.getItem(key)) || null;
    return _data
  },
  clear(key){
    if(!window.localStorage){
      return
    }
    localStorage.removeItem(key)
  }
}
export {
  storage
}

欢迎大家来找bug,后面的文章我会奉上完整版storage方法,有想说的留言给我。

最近发表
标签列表