封装localStorage 和 sessionStorage

class EricCache{
    constructor(isLocal = true){
        this.stroage = isLocal ? localStorage : sessionStorage
    }

    setItem(key,value){
        if(value){
            this.stroage.setItem(key,JSON.stringify(value))
        }
    }

    getItem(key){
        const value = this.stroage.getItem(key)
        if(value){
            value = JSON.parse(value)
            return value
        }
    }

    removeItem(key){
        this.stroage.removeItem(key)
    }

    clear(){
        this.stroage.clear()
    }

    key(index){
        return this.stroage.key(index)
    }

    length(){
        return this.stroage.length
    }


}

const localCache = new EricCache()
const sessionCache = new EricCache(false)

export {
    localCache,
    sessionCache
}
posted @ 2022-01-25 14:39  13522679763-任国强  阅读(34)  评论(0)    收藏  举报