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)

 

上一篇:Node.js服务端开发总结(一)


下一篇:实验周--安装mysql