scope and closure

<script>this

var i;spa


var resetI = function()three

{ip

   i = 1;it

};io




function Counter(){function

this.i = window["i"] + 10;co

   return {script

      inc: function(){++i;},new

      dec: function(){i--;},

      value: function(){return i;}

   };

};




function Counter2(){

    this.i = window["i"] + 10;

    this.inc = function(){++i;};

    this.dec = function(){--i;};

    this.value = function(){return i;};

}


function Counter3(){

    this.i = window["i"] + 10;

   return function(i){

      return{

      inc: function(){++i;},

      dec: function(){i--;},

      value: function(){return i;}

      }

  }(this.i);

}


resetI();


var one = new Counter();

one.inc();

one.inc();

one.dec();

alert(one.value());//2

var two = Counter();

two.inc();

alert(one.value());//13

alert(two.value());//13


resetI();


var three = new Counter2();

three.inc();

three.inc();

three.dec();

alert(three.value());//2

var four = Counter2();

//four.inc();  //complain undefined

inc();

alert(three.value());//13

//alert(four.value());  //complain undefined

alert(value());//13



resetI();


var five = new Counter3();

five.inc();

five.inc();

five.dec();

alert(five.value());//12

var six = Counter3();

six.inc();

six.inc();

six.inc();

alert(five.value());//12

alert(six.value());//14


resetI();


</script>

相關文章
相關標籤/搜索