JavaScript應用數據緩存對象申明

JavaScript應用數據緩存對象申明,做到無數據時自動調用對應函數獲取數據並緩存,當再次獲取數據時,直接從緩存中獲取。

(function(){
    var cacheObject={};
    Object.defineProperty(window,'AppDataCache',{
    writable: false,
    enumerable: false,
    configurable: false,
    value: {}
    });
    Object.defineProperties(AppDataCache,{
        add: {
        writable: false,
        enumerable: false,
        configurable: false,
        value: function(key, data_fn){
            debugger;
            var obj = {};
            if(typeof(key)==='string'){
                obj[key]=data_fn;
            } else if(typeof(data_fn)==='string') {
                obj[data_fn]=key;
            } else if(key && typeof(key)==='object') {
                obj=key;
            }
            for(var k in obj) {
                if(k=='add' || k=='clear')throw Error("add key name can't equals [add,clear]");
                if(cacheObject.hasOwnProperty(k) && console && console.warn) {
                    delete cacheObject[k];
                    console.warn("Already exist["+k+"],Cover this key data");
                }
                (function(k_,data_){
                    Object.defineProperty(AppDataCache,k_,{
                        //writable: true,
                        enumerable: true,
                        configurable: true,
                        get: function(){
                            if(!cacheObject[k_]){
                                cacheObject[k_]=typeof(data_)==='function'?data_():data_;
                            }
                            return cacheObject[k_];
                        }
                    });
                })(k,obj[k])
            }
        }
      },
      clear: {
        writable: false,
        enumerable: false,
        configurable: false,
        value: function(key){
            if(key) {
                return delete cacheObject[key];
            }
            for(var k in cacheObject){
                delete cacheObject[k];
            }
            return true;
        }
      }
    });
})()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章