jQuery缓存实现的分析-及源码解读

来源:互联网 发布:唱歌调音软件 编辑:程序博客网 时间:2024/06/06 14:13
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script>        //eleCache        //typeCache        //classCache        //eventCache        function createCache(){            //cache对象中以键值对的形式存储我们的缓存数据            var cache = {};            //index数组中该存储键,这个键是有顺序,可以方便我们做超出容量的处理            var index = [];            return function (key, value) {                //如果传了值,就说名是设置值                if(value !== undefined){                    //将数据存入cache对象,做缓存                    cache[key] = value;                    //将键存入index数组中,以和cache中的数据进行对应                    index.push(key);                    //判断缓存中的数据数量是不是超出了限制                    if(index.length >= 50){                        //如果超出了限制                        //删除掉最早存储缓存的数据                        //最早存入缓存的数据的键是在index数组的第一位                        //使用数组的shift方法可以获取并删除掉数组的第一个元素                        var tempKey = index.shift();                        //获取到最早加入缓存的这个数据的键,可以使用它将数据从缓存各种删除                        delete cache[tempKey];                    }                }                //如果没有传值,只穿了键,那就是获取值//                else{//                    return cache[key];//                }                return cache[key];            }        }        var eleCache = createCache();        eleCache("name","张小三");        console.log(eleCache("name"));        var typeCche = createCache();//------------------------源码解读----------------------------------------     function createCache() {        var keys = [];        function cache( key, value ) {            // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)            // 使用(key + " ") 是为了避免和原生(本地)的原型中的属性冲突            if ( keys.push( key + " " ) > 3 ) {                // Only keep the most recent entries                // 只保留最新存入的数据                delete cache[ keys.shift() ];            }            // 1 给 cache 赋值            // 2 把值返回            return (cache[ key + " " ] = value);            // cache[key + ""] = value;            // return value;        }        return cache;    }        var typeCache = createCache();        typeCache("monitor");        console.log(typeCache["monitor" + " "]);        typeCache("monitor","张学友");        console.log(typeCache["monitor1" + " "]);        typeCache("monitor","刘德华");        console.log(typeCache["monitor2" + " "]);        typeCache("monitor3","彭于晏");        console.log(typeCache["monitor3 "]);//        console.log(typeCache["monitor "]);    </script></head><body></body></html>

阅读全文
0 0
原创粉丝点击