We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

back to the lesson

Counter object

importance: 5

Here a counter object is made with the help of the constructor function.

Will it work? What will it show?

function Counter() { let count = 0; this.up = function() { return ++count; }; this.down = function() { return --count; }; } let counter = new Counter(); alert( counter.up() ); // ? alert( counter.up() ); // ? alert( counter.down() ); // ?

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