论坛首页 入门技术论坛

JavaScript内核系列 第7章 闭包

浏览 11871 次
该帖已经被评为新手帖
作者 正文
   发表时间:2010-05-06  
第八章 面向对象的JavaScript http://www.iteye.com/topic/660049
0 请登录后投票
   发表时间:2010-05-06  
非常易于理解
0 请登录后投票
   发表时间:2010-05-06  
啊哦,马上要被投成新手帖了!本来打算将闭包放在函数式编程那一章的,但是有朋友建议独立出来,结果独立出来后内容显得有些单薄,呵呵。
0 请登录后投票
   发表时间:2010-05-11  
有点不明白的,7.2.3中的2个例子的var person = function(){...}();var person = function(){...};有什么区别?好像就只是多了个小括号而已。
var person = function(){  
    //变量作用域为函数内部,外部无法访问  
    var name = "default";     
     
    return {  
       getName : function(){  
           return name;  
       },  
       setName : function(newName){  
           name = newName;  
       }  
    }  
}();  
   
print(person.name);//直接访问,结果为undefined  
print(person.getName());  
person.setName("abruzzi");  
print(person.getName());

var person = function(){
    var name = "default";     
     
    return {  
       getName : function(){  
           return name;  
       },  
       setName : function(newName){  
           name = newName;  
       }  
    }  
};     
   
var john = person();  
print(john.getName());  
john.setName("john");  
print(john.getName());  
   
var jack = person();  
print(jack.getName());  
jack.setName("jack");  
print(jack.getName()); 
0 请登录后投票
   发表时间:2010-05-11  
yyg1107 写道
有点不明白的,7.2.3中的2个例子的var person = function(){...}();var person = function(){...};有什么区别?好像就只是多了个小括号而已。


一个是变量声明,一个是匿名调用。
嗯,这儿起同样的名字确实让人混淆。
0 请登录后投票
   发表时间:2010-05-19  

看了你写的,自己也照着写一个可实现缓存的东东。欢迎拍砖 :P

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");
}

 

0 请登录后投票
   发表时间:2010-08-11  
恩,写的不错啊。。。。支持
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics