`
liushilang
  • 浏览: 86238 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

可实现缓存的一个JS类

阅读更多
测试通过
var adder = function(n){
	var t = 10;
	var org = n+"-"+Math.random();
	return{ 
		getinfo:function(){
			document.writeln("\n\t"+org);
			return n+t;
		  }
	   };
 };

var CachedSearchBox = (function(){
	var cache = {},count = [],totalCount = 20;
	
	return {
		attachSearchBox:function(dsid){
		  if(dsid in cache){
			 print("old:::"+cache[dsid].getinfo());
			return cache[dsid];
		}
		var fsb = new adder(dsid);
		print("new::::"+fsb.getinfo());
		cache[dsid] = fsb;
		if(count.length>=totalCount){		    
			var out = count.shift();
			print("del::::::::::::"+out.getinfo())
			delete cache[out];
		}
		count.push(fsb);
		return fsb;
	  },
	   clearSearchBox:function(dsid){
		if(dsid in cache){
			//cache[dsid].clearSelection();
			delete cache[dsid];
			count.shift();
		}
	  },
	  getcount:function(){//获取对象的长度
	    print("array length:"+count.length);
		return count.length;
	  },
	  setTotalCount:function(c){//设置缓存大小
		totalCount = c;
	  }
};
})();

CachedSearchBox.getcount();
print("<br>");

(function(){
   for(var i=0;i<100;i++){
     CachedSearchBox.attachSearchBox(Math.ceil(Math.random()*120))
	  print("~~~~~");
	  CachedSearchBox.getcount();
      print("<br>");
	  if(i==30)
		CachedSearchBox.setTotalCount(40);
   }
})();

function print(a1){
	document.writeln(a1+"\n\t");
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics