localStorage和sessionStorage原型方法新增

hackLi發表於2019-03-29

這次主要是Storage原型中新增自己的方法

物件原型中新增一個鏈

/**
 * 物件原型中新增一個鏈
 * @parma oChain 當前物件
 * @parma oProto 鏈
 */
Reflect.appendChain = function(oChain, oProto) {
  if (arguments.length < 2) { 
    throw new TypeError('Object.appendChain - Not enough arguments');
  }
  if (typeof oProto === 'number' || typeof oProto === 'boolean') {
    throw new TypeError('second argument to Object.appendChain must be an object or a string');
  }

  var oNewProto = oProto,
      oReturn, 
      o2nd, 
      oLast;
	  
  oReturn = o2nd = oLast = oChain instanceof Object ? oChain : new oChain.constructor(oChain);

  for (var o1st = this.getPrototypeOf(o2nd);
    o1st !== Object.prototype && o1st !== Function.prototype;
    o1st = this.getPrototypeOf(o2nd)
  ) {
    o2nd = o1st;
  }

  if (oProto.constructor === String) {
    oNewProto = Function.prototype;
    oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1));
    this.setPrototypeOf(oReturn, oLast);
  }

  this.setPrototypeOf(o2nd, oNewProto);
  return oReturn;
}
複製程式碼

自定義方法(Storage可以新增陣列了)

function StorageMethod() {}
				
StorageMethod.prototype = {
    getStorage(sname, defaultValue){
        var result = this.getItem(sname);
        return result || defaultValue;
    },
    setStorage(sname, svalue){
        if(Array.isArray(svalue)) {
        svalue = svalue.join("|");
        }
        this.setItem(sname, svalue);
        },
        getStorageArray(sname) {
        return this.getItem(sname).split("|");
    },
    getAllKeys(){
        var arr = [];
        for(var i=0;i<this.length;i++){
            arr.push(this.key(i));
        }
        return arr;
    }
}
複製程式碼

使用

localStoragesessionStorage新增自定義方法,這個方法類似拷貝繼承

if(!window.localStorage || !window.localStorage){
    alert('your browser is not support Storage!');
    return;
}
// localStorage和sessionStorage新增StorageMethod的方法
Reflect.appendChain(window.localStorage, new StorageMethod());
Reflect.appendChain(window.sessionStorage, new StorageMethod());
複製程式碼

測試

window.sessionStorage.setStorage("test", [112,2,'ds'])
console.log(window.sessionStorage.getStorageArray("test"))
複製程式碼

相關文章