在日常的项目开发中我们经常会抽离封装一些工具方法,以便多模块复用,这是好的习惯,但,如果你封装的方法 有 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方法,有想说的留言给我。