class Cache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setCache(key, value) {
if (!value) {
throw new Error('value error: value 必须有值')
}
if (value) {
localStorage.setItem(key, JSON.stringify(value))
}
}
getCache(key) {
const result = this.storage.getItem(key)
if (result) {
return JSON.parse(result)
}
}
removeCache(key) {
this.storage.removeItem(key)
}
clearCache(key) {
this.storage.clear()
}
}
const localCache = new Cache()
const sessionCache = new Cache(false)
const info = {
name:'www',
age:19
}
sessionCache.setCache('info',info)
localCache.getCache(info)