en.javascript.info/1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md
Ilya Kantor 964ed57c42 closure
2019-12-26 14:59:57 +03:00

439 B

Surely it will work just fine.

Both nested functions are created within the same outer Lexical Environment, so they share access to the same count variable:

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