var Cache = function(max, buffer) { this.$cache = []; this.$max = max | 0 || 20; this.$buffer = buffer | 0 || 5; }; Cache.prototype.set = function(key, cacheItem) { var cache = this.$cache; key = 'cache_' + key; var temp = cache[key]; if (!cache.hasOwnProperty(key)) { if (cache.length >= this.$max + this.$buffer) { //缓存列表和缓冲区都满了 cache.sort(function(a, b) { return b.fre == a.fre ? b.time - a.time : b.fre - a.fre; }); var counter = this.$buffer; while (counter--) { //缓冲区有多少,我们就一次性删除多少 var item = cache.pop(); delete cache[item.key]; } } temp = {}; cache.push(temp); cache[key] = temp; } temp.item = cacheItem; temp.fre = 1; temp.key = key; temp.time = new Date().getTime(); return temp; }; Cache.prototype.get = function(key) { key = 'cache_' + key; var cache = this.$cache; var result; if (cache.hasOwnProperty(key)) { result = cache[key]; if (result.fre >= 1) { result.fre++; result.time = new Date().getTime(); result = result.item; } } return result; }; Cache.prototype.has = function(key) { key = 'cache_' + key; return this.$cache.hasOwnProperty(key); }; Cache.prototype.del = function(key) { key = 'cache_' + key; var cache = this.$cache; var result = cache[key]; if (result) { result.fre = -1; delete result.item; delete cache[key]; } };