en.javascript.info/1-js/8-more-functions/03-closure/2-counter-object-independent/solution.md
Ilya Kantor 3defacc09d up
2016-11-12 19:38:58 +03:00

380 B

Both nested functions are created within the same Lexical Environment.

So they share the same count:

function Counter() {
  let count = 0;

  this.up = function() {
    return ++count;
  };
  this.down = function() {
    return --count;
  };
}

let counter = new Counter();

alert( counter.up() ); // 1
alert( counter.up() ); // 2
alert( counter.down() ); // 1