jQuery最基本的缓存结构,你们应该都清楚,例如:var cache = {}; 怎么去实现缓存的设置和获取呢?咱们要先解决这个问题! 缓存
案例:实现缓存的设置和获取prototype
// 设置var fn = function(k, v) { cache[k] = v;}; // 获取// 1 var cacheValue = cache[k];// 2 var getV = function(k) { return cache[k];};
缓存注意事项get
1 缓存数量要在必定范围内,例如:100条原型
2 缓存数据要可控,增删改查it
3 缓存须要被保护io
实现缓存数据function
var createCache = function(){ var internalCache = {}; var arr = []; return function (k, v) { if(v) { if(!internalCache[k]) { if(arr.length >= 50) { var deleteKey = arr.shift(); delete internalCache[k]; } arr.push(k); } internalCache[k] = v; } else { return internalCache[k]; } };};
jQuery中缓存的实现im
/** * Create key-value caches of limited size * 建立带有长度限制的键值对缓存 */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 + " " ) > Expr.cacheLength ) { // Only keep the most recent entries // 只保留最新存入的数据 delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache;} var typeCache = createCache(); typeCache("cls", "stra");typeCache["cls"];