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"];