Javascript Property accessor methods:getter & setter

 1 function counter(n){ //Function argument n is the private variable
 2                 return{
 3                     //Property getter method returns and increments private counter var.
 4                     get count(){return n++;},
 5                     //Property setter doesn't allow the value of n to decrease
 6                     set count(m){
 7                         if(m>=n)n=m;
 8                         else throw Error("count can only be set to a larger value");
 9                     }
10                 };
11             }
12             var c=counter(1000);
13             c.count;//=>1000
14             c.count;//=>1001
15             c.count=2000;
16             c.count;//=>2000
17             c.count;//throw error

 

posted @ 2013-01-15 16:14  arthur_d  阅读(183)  评论(0编辑  收藏  举报