闭包捕捉单个函数调用时的局部变量,并将其当做私有变量使用

1 uniqueInteger.counter = 0;
2 function uniqueInteger(){
3     return uniqueInteger.counter++;
4 }

we defined a uniqueInteger() function that used a property of the function itself to keep track of the next value to be returned. A shortcoming of that approach is that buggy or malicious code could reset the counter or set it to a noninteger, causing the uniqueInteger() function to violate the “unique” or the “integer” part of its con-tract. Closures capture the local variables of a single function invocation and can use those variables as private state. Here is how we could rewrite the uniqueInteger() function using closures:

 1 var uniqueInterger = (function(){//define and invoke
 2 
 3     var counter=0; //private state of function below
 4 
 5     return function(){
 6 
 7         return counter++;
 8 
 9     };
10 
11 }());

 

posted @ 2013-01-14 19:58  arthur_d  阅读(130)  评论(0编辑  收藏  举报