封装localStorage/sessionStorage

915 阅读1分钟
说到localStorage,很多人都喜欢直接用。保存对象的时候,有些新手会忽略到对象是直接保存时会转成字符"[object Object]",要先转成JSON字符。 读取JSON字符串时也要进行JSON格式化成对象。经常遇到一些人写代码是这样:localStorage.setItem('someInfo',JSON.stringify(someObj)) 或者是JSON.parse(localStorage.getItem('someInfo'))。其实这样写,不够优雅。 如果你的项目里有很多这样的localStorage.setItem,如果让你把localStorage替换sessionStorage了,你得全局替换。如果是有很多sessionStorage,又得全局替换。如果项目中又有localStorage和sessionStorage,这时候就头大(麻烦)了。这时候就想方法封装了。

我思路是分别给字符和对象 定义读取与设置 的方法,同时保留原来的Item方法。

首先可以先定一个构造函数:

function MyStorage(storageObj) {  
  this.storageObj = storageObj;
  this.strArrObjReg = /^[\[{][\w\W]*[\]}]$/g; /* 只是简单匹配字符正则,未做严格匹配 */ 
}

接下来改给这个构造函数添加方法:

先来保留基本的方法:

MyStorage.prototype.getItem = function (key) {  return this.storageObj.getItem(key)}
MyStorage.prototype.setItem = function (key, value) { this.storageObj.setItem(key, value)} 
MyStorage.prototype.removeItem = function (key) { this.storageObj.removeItem (key)}

划重点:获取对象;

MyStorage.prototype.getObject=function  (key) {      
  let currentValue = this.getItem(key);        
  let isJSON_obj =  this.strArrObjReg.test(currentValue);  
  if (isJSON_obj) {
    return JSON.parse(currentValue)
  }else {
    throw new Error('expect Object/Array, got other')  
  }
}

设置对象:

MyStorage.prototype.setObject=function (key, value, isNeedTimeStamp) { 
 if (value && typeof value === 'object') {
  this.storageObj.setItem(key, JSON.stringify(value));//JSON格式化    
 } else { 
    throw new Error('expect Object, got other')}}

获取字符:

MyStorage.prototype.getString=function(key) {
 let storageValue=this.getItem(key);
 if(!this.strArrObjReg.test(storageValue)){  
   return  storageValue
 }else{
   throw new Error('expect String, got other')
 }}

设置字符:

MyStorage.prototype.setString=function(key, value) { 
  if(typeof value==='string'||typeof value==='number'||typeof value==='boolean' ){ 
     this.setItem(key, value)
  }else{ 
    throw new Error('expect String Number Boolean, got other')
  }
}

还可以保存时间戳:

MyStorage.prototype.setTimeStamp=function(key) {
  let timeStamp = + new Date();  
  this.setItem(key + '_date', timeStamp + '')
}

获取时间戳:

MyStorage.prototype.getTimeStamp=function((key){  
    return  this.getItem(key + '_date')
}

来一点异步也是可以保存对象:

MyStorage.prototype.getObjectAsync = function(key){  
  let currentValue = this.getItem(key);  
  let isJsonObj = this.strArrObjReg.test(currentValue);  
  return new Promise((resolve, reject) => {   
    if (isJsonObj ) {            
        let jsonValue = JSON.parse(currentValue)    
        resolve(jsonValue)   
     } else {     
         reject({message: key+' expect Object/Array, got other'})
    }  
 })
}

异步读取对象:

MyStorage.prototype.setObjectAsync= function (key,value){  
    return new Promise((resolve, reject) => {   
     if (value && typeof value === 'object') { 
       let resultStr=JSON.stringify(value); //JSON格式化  
       this.setItem(key, resultStr);  
       resolve(resultStr) 
    }else {
       reject({message: key+' expect Object/Array, got other' }) 
    }  
  })
}

最后实例化即可调用方法:

let longStorage = new MyStorage(localStorage)
let shortStorage = new MyStorage(sessionStorage)

如有需要再导出:

export {longStorage,shortStorage }


文章最后附上完整的代码:

function MyStorage(storageObj) {  
    this.storageObj = storageObj;
    this.strArrObjReg = /^[\[{][\w\W]*[\]}]$/g;
}
MyStorage.prototype = {  
   getItem(key) {    
        return this.storageObj.getItem(key)  
   },
   setItem(key, value) {  
      this.storageObj.setItem(key, value)  
   }, 
   removeItem(key){   
     this.storageObj.removeItem(key) 
   },  
   setTimeStamp(key) {    
    let timeStamp = +new Date();    
    this.setItem(key + '_date', timeStamp + '') 
   },
   getTimeStamp(key){ 
     return  this.getItem(key + '_date')
  }, 
   setString(key, value) {  
     if(typeof value==='string'||typeof value==='number'||typeof value==='boolean' ){ 
       this.setItem(key, value) 
     }else{    
       throw new Error('expect String Number Boolean, got other')
     } 
   }, 
   getString(key){
     let storageValue=this.getItem(key);   
      if(!this.strArrObjReg.test(storageValue)){  
         return  storageValue 
      }else{ throw new Error('expect String, got other') }
    },  
   getObject(key) {   
        let currentValue = this.getItem(key);  
        let isJsonObj= this.strArrObjReg.test(currentValue);          if (isJsonObj) {                return JSON.parse(currentValue)  
        } else {     
           throw new Error('expect Object/Array, got other')  
       } 
   },  
   setObject(key, value) {  
         if (value && typeof value === 'object') {   
             this.storageObj.setItem(key, JSON.stringify(value));//JSON格式化   
         } else {
         throw new Error('expect Object/Array, got other') 
   }}, 
   getObjectAsync(key){   
       let currentValue = this.getItem(key);
       let isJsonObj = this.strArrObjReg.test(currentValue);  
        return new Promise((resolve, reject) => {      
          if (isJsonObj) {       
             let jsonValue = JSON.parse(currentValue)    
             resolve(jsonValue)     
          } else {        
             reject({message: key+' expect Object/Array, got other'})     
          }    
       }) 
   }, 
   setObjectAsync(key,value){    
       return new Promise((resolve, reject) => { 
          if (value && typeof value === 'object') {        
            let resultStr=JSON.stringify(value); //JSON格式化        
            this.storageObj.setItem(key, resultStr);       
            resolve(resultStr)
          } else {
             reject({message: key+' expect Object/Array, got other'})      
           } 
       }) 
   }
};

ES6的:

class MyStorage{ 
 constructor(storageObj) {  
  this.storageObj = storageObj;   
  this.strArrObjReg = /^[\[{][\w\W]*[\]}]$/g; 
 } 
  /* ... 此处省略一万字...*/
}