大前端

jQuery中缓存函数分析

2017-03-23  本文已影响12人  oldSix_Zhu

若有不妥,请多指教

jQuery中缓存函数
模拟jQuery的缓存实现

这个函数更容易理解,但是不简洁
看懂这个函数后,jQuery中的缓存函数就容易理解了

<script>
    function createCache() {
        //缓存对象(类似字典的键值对形式)
        var cache = {};
        //缓存数据的key数组
        var index = [];
        function caches(key, value) {
            //如果传进来的是key与数据且有值,就说明要缓存该数据
            if (value !== undefined)
            {
                //将数据存入缓存对象中
                cache[key] = value;
                //将数据对应的key存入数组中
                index.push(key);
                //根据数据的key多少,定义缓存的大小
                if (index.length > 10)
                {
                    //删除最早存入的数据,即数组第一个key对应的数据
                    var k = index.shift();
                    delete  cache[k];
                }
            }
            //如果传进来的是key,根据key返回数据
            return cache[key];
        }
        return caches;
    }

    var test = createCache();
    test("0","邱淑贞");
    test("1","王祖贤");
    console.log(test("0"),test("1"));//打印:邱淑贞 王祖贤
</script>
jQuery中缓存函数分析
<script>
    function createCache() {
        var keys = [];
        function cache(key ,value) {
            // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
            //key的名字后加个空格完美避免和原生原型中的属性名重名
            //也要判断缓存最大数量,这里写固定的10个
            if (keys.push(key + " ") > 10)
            {
                // Only keep the most recent entries
                //只保留最新存入的数据
                delete cache[keys.shift()];
            }
            //把这个cache()函数当做缓存对象容器直接使用了
            //所以没有定义cache = {};
            //减少了变量的声明
            return(cache[key + " "] = value);
        }
        return cache;
    }

    var test = createCache();
    test("a","邱淑贞");
    test("b","王祖贤");
    console.log(test["a" + " "],test["b" + " "]);//打印:邱淑贞 王祖贤
</script>
上一篇 下一篇

猜你喜欢

热点阅读