JS 使用localStorage或者sessionStorage 实现cookie功能

    class Storage{
      setItem(name,data,time){
        let startTime=new Date().getTime()
        let obj={
          data:data,
          endTime:startTime+time*60*60*1000,                //单位小时
        }
        localStorage.setItem(name,JSON.stringify(obj))
      }
      getItem(name){
        let obj=localStorage.getItem(name)
        if(obj){
          obj=JSON.parse(obj)
          let nowTime=new Date().getTime();
          if(nowTime>obj.endTime){
            this.removeItem(name)
          }else{
            return obj
          }
        }
      }
      removeItem(name){
        localStorage.removeItem(name)
      }
      clear(){
        localStorage.clear()
      }
    }
    const storage= new Storage();
    let data={
      name:'zhangsan',
      age:33
    }
    storage.setItem('userInfo',data,1)
    let userInfo=storage.getItem('userInfo')
    console.log(userInfo)

 

posted @ 2022-02-28 14:22  伴月阁  阅读(74)  评论(0编辑  收藏  举报