Let's rewrite our code so that the
returned function increments the
value of the variable num
by one each time:
function test() {
let num = 1;
return function() {
console.log(num);
num++; // adds one
}
}
let func = test();
It turns out that each call to the function
func
will output a new
value to the console:
function test() {
let num = 1;
return function() {
console.log(num);
num++;
}
}
let func = test();
func(); //shows 1
func(); //shows 2
func(); //shows 3
func(); //shows 4
func(); //shows 5
It turns out that we implemented the function
call counter using a closure (more precisely,
using the variable num
from our
function closure).
Note that each call to the function test
will return a new function that will have
its own closure. That is, different counters
will work independently:
function test() {
let num = 1;
return function() {
console.log(num);
num++;
};
}
let func1 = test(); // the first counter
func1(); //shows 1
func1(); //shows 2
let func2 = test(); // the second counter
func2(); //shows 1
func2(); //shows 2
It turns out that the same variable num
will have different values for
different functions!
That is, if we call the function test
twice, then the functions derived from it will
work independently and each of these functions
will have its own independent variable num
.
On your own, without looking into my code, implement a function call counter that works on closures.
Let the function store the number 10
in the closure. Make it so that each
function call decrements this number
by 1
and prints the decremented
number to the console.
Modify the previous task so that the
countdown goes up to 0
, and then
each subsequent function call prints a
message to the console that the
countdown has ended.