Let's take the variable num
out of
functions, thereby making it global:
let num = 1; // the global variable
function test() {
return function() {
console.log(num);
num++;
};
};
In this case, all returned functions will change this global variable and the counters will work already depending on each other:
let num = 1;
function test() {
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 3
func2(); //shows 4
Why did our previous code make independent counters? Recall this code:
function test() {
let num = 1;
return function() {
console.log(num);
num++;
};
}
The point is that the variable num
is local inside the function test
.
Therefore, each call to test
generates
its own local variable.
Therefore, the each of returned functions will
refer to its local function variable test
.
This is how independence is achieved.
If we make num
a global variable,
this will also be a closure. It's just
that the lexical environments of returned
functions refer to the same variable
num
- any changes to this variable
will be visible in all functions.
Determine what will be output to the console without running the code:
let counter = 0;
function test() {
return function() {
console.log(counter);
counter++;
};
};
let func = test;
let func1 = func();
let func2 = func();
func1();
func2();
func1();
func2();
Determine what will be output to the console without running the code:
function test() {
let counter = 0;
return function() {
return function() {
console.log(counter);
counter++;
};
};
}
let func = test()();
let func1 = func;
let func2 = func;
func1();
func2();
func1();
func2();
Determine what will be output to the console without running the code:
function test() {
let counter = 0;
return function() {
return function() {
console.log(counter);
counter++;
};
};
}
let func = test();
let func1 = func();
let func2 = func();
func1();
func2();
func1();
func2();