---
title: "close package"
author: "dmwdmc"
date: "2013-06-13T17:54:52Z"
tags: []
categories: ["Web前端"]
slug: "close-package"
draft: false
lastmod: "2013-06-13T18:12:46Z"
id: 1886293
url: "https://dmwdmc.iteye.com/blog/1886293"
---

即返回是个函数


> <script>
> function a(){
>  var i=0;
>  function b(){
>  alert(++i);
>  }
>  return b;
> }
> var c = a();
> c();
> c();
> c();
> c();
> c();
> </script>


页面就输出1,2,3,4,5

整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c，又函数b的作用域链包含了对函数a的活动对象的引用，也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用，函数b又依赖函数a，因此函数a在返回后不会被GC回收。

但是如果这么写。

> <script>
> function a(){
>  var i=0;
> 	
>  return b(i);
> }
> 
>  function b(k){
>  alert(++k);
>  }
> a();
> a();
> a();
> </script>


就只能是１，１，１

以下就能把变量存在缓存中，可以在接下来用。

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