即返回是个函数
[quote]<script>
function a(){
var i=0;
function b(){
alert(++i);
}
return b;
}
var c = a();
c();
c();
c();
c();
c();
</script>[/quote]
页面就输出1,2,3,4,5
整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b又依赖函数a,因此函数a在返回后不会被GC回收。
但是如果这么写。
[quote]<script>
function a(){
var i=0;
return b(i);
}
function b(k){
alert(++k);
}
a();
a();
a();
</script>[/quote]
就只能是1,1,1
以下就能把变量存在缓存中,可以在接下来用。
[quote]var CachedSearchBox = (function(){
var cache = {},
count = [];
return {
attachSearchBox : function(dsid){
if(dsid in cache){//如果结果在缓存中
return cache[dsid];//直接返回缓存中的对象
}
var fsb = new uikit.webctrl.SearchBox(dsid);//新建
cache[dsid] = fsb;//更新缓存
if(count.length > 100){//保正缓存的大小<=100
delete cache[count.shift()];
}
return fsb;
},
clearSearchBox : function(dsid){
if(dsid in cache){
cache[dsid].clearSelection();
}
}
};
})();
CachedSearchBox.attachSearchBox("input1"); [/quote]
[quote]<script>
function a(){
var i=0;
function b(){
alert(++i);
}
return b;
}
var c = a();
c();
c();
c();
c();
c();
</script>[/quote]
页面就输出1,2,3,4,5
整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b又依赖函数a,因此函数a在返回后不会被GC回收。
但是如果这么写。
[quote]<script>
function a(){
var i=0;
return b(i);
}
function b(k){
alert(++k);
}
a();
a();
a();
</script>[/quote]
就只能是1,1,1
以下就能把变量存在缓存中,可以在接下来用。
[quote]var CachedSearchBox = (function(){
var cache = {},
count = [];
return {
attachSearchBox : function(dsid){
if(dsid in cache){//如果结果在缓存中
return cache[dsid];//直接返回缓存中的对象
}
var fsb = new uikit.webctrl.SearchBox(dsid);//新建
cache[dsid] = fsb;//更新缓存
if(count.length > 100){//保正缓存的大小<=100
delete cache[count.shift()];
}
return fsb;
},
clearSearchBox : function(dsid){
if(dsid in cache){
cache[dsid].clearSelection();
}
}
};
})();
CachedSearchBox.attachSearchBox("input1"); [/quote]