封装localStorage实现缓存过期

在localStorage是h5中很好用的功能,有着比cookie更快速且容量更大的特性,如果频繁的读取和存储数据,而数据有json,有字符串,就会照成大量代码冗余,封装一起就看起来好很多!

下面我要对localStorage进行二次封装,实现缓存过期的功能,下面直接贴出代码,共有需要的人参考

    var local = {
        get: function(name){
            var obj = localStorage.getItem(name) || ''
            var cut = obj.indexOf(';expiretime=')
            var expiretime = obj.substring(cut)
            var val = obj.substring(0, cut < 0? cut.length : cut)
            if(expiretime){
                console.log(expiretime)
                expiretime = expiretime.substring(12)
                if(expiretime < this.time()){
                    //已经过期
                    alert('已过期,删除所有数据')
                    local.clear(name);
                    return ''
                }else{
                    //未过期
                    alert('未过期')
                    return this.back(val)
                }
            }
        },

        back: function(val){
            if( val === "" || val.indexOf('{') && val.indexOf('}') ){
                return val
            }else{
                return  JSON.parse(val)
            }
        },

        set: function(name, val, expireTime){
            //如何存储的是对象,对象和字符出字符串拼接
            //[object Object];expiretime= 1520689159000
            //{"name":"weihong"};expiretime= 1520689584000
            val = typeof(val) === 'object' ? JSON.stringify(val) : val
            if(expireTime){
                val +=';expiretime= ' + (this.time() +expireTime * 1000 )
            }
            localStorage.setItem(name,val)
        },

        clear: function(name){
            console.log('删除所有数据')
            localStorage.removeItem(name)

        },
        time: function(){
            return Date.parse(new Date())//1520687826000
        }

    }

    local.set('name',{name:'weihong'},1)
    // local.set('name', 'weihong',1)
    console.log(local.get('name'))

你可能感兴趣的:(封装localStorage实现缓存过期)