用 JSON和userData 更全面的模拟 localStorage

上编文中讲的 封装, 只实现了 setItem, getItem, removeItem接口。 如果要实现 key()和length 就不行, 也就是说如果你需要遍历的功能,那么需要选择别的方式。

这次我打算损失点性能来模拟。借助 JSON 来保存 对象。

 

代码

if(!window.localStorage && /MSIE/.test(navigator.userAgent)){
    window.localStorage=(function(){
        var file_name="user_data_default";
        var dom = document.createElement('input');
        dom.type = "hidden";
        dom.addBehavior ("#default#userData");
        document.body.appendChild(dom);
        dom.save(file_name);

        var local_storage = function(){};

        var storage={};
        var keys = [];

        function load_store_object(){
            dom.load(file_name);
            var txt = dom.getAttribute("storage");
            try {
                if(txt && txt.length >0) {
                    storage = JSON.parse(txt);
                } else {
                    storage = {};
                }
            } catch(e)
            {
                storage = {};
            }
        }

        function save_store_object(){
            var txt = JSON.stringify(storage);
            dom.setAttribute("storage", txt);
            dom.save(file_name);
        }

        function get_keys(obj) {
            var keys=[];
            for(var k in obj) {
                keys.push(k);
            }
            return keys;
        }


        function gen_index(){
            keys = get_keys(storage);
            local_storage.prototype.length = keys.length;
        }


        local_storage.prototype ={
            setItem:function(k, v)
            {
                load_store_object();
                storage[k]=v;
                save_store_object();
                gen_index();
            },
            getItem:function(k){
                load_store_object();
                gen_index();
                return storage[k];
            },
            removeItem:function(k){
                load_store_object();
                delete storage[k];
                gen_index();
                save_store_object();
            },

            clear:function(){
                storage={};
                save_store_object();
                gen_index();
            },

            key:function(i) {
                return keys[i];
            },

            storage:function(){
                return storage;
            },

            dom:function() {
                return dom;
            }
        }

        load_store_object();
        gen_index();
        return new local_storage();
    })();
}

缺陷

依赖json2.js库,存取数据的效率会低一些,而且还是不同通过 localStorage.your_attr 来存取,  因为ie6不支持 __defineGetter__ 等方法。

你可能感兴趣的:(localStorage)