var aaa= function(){ }
    
  aaa.prototype = 
{
 count:0,
add:this.count++;
 }var b = new aaa();
alert(b.count);
b.count = 3;//这一步我想让他报错,应该不能设置这个count属性
alert(b.count);
请问大家应该怎么写?

解决方案 »

  1.   


    <script type="text/javascript">
    <!--
    var aaa = function(){
    var count = 0;
    return {
    get_count: function(){
    return count;
    },
    set_count: function(_count){
    count = _count;
    }
    };
    };var b = aaa();
    alert(b.get_count());
    b.count = 3;
    alert(b.get_count());//-->
    </script>
      

  2.   

    count:function () { return 0;},
      

  3.   


    UP,UP,通过公用方法来访问私有变量count!
      

  4.   


    但这样没法用b.count来取值啊,我希望是用b.count来取值,但不能用b.count赋值,就像obj.parentNode一样,只能读取而不能赋值.
      

  5.   

    不能通过属性实现,只能通过方法.
    如果你想通过this.count属性来取值,那么就一定可以这样赋值.
    所以还是改用this.count()来取值吧.
      

  6.   

    饿··那obj.parentNode是如何实现的呢?它为什么是只能读取的呢..
      

  7.   

    因为现在使用的JavaScript版本还没有实现get和set(有些浏览器的脚本引擎已经实现了,比如Safari)