I try to figure out, how closure works, this is my example
function func1(func) {
return function(summand) {
return func() + summand;
}
}
var func2 = function() {
return 3;
}
var func3 = func1(func2);
var value = func3(4);
alert(value);
var func2 = function() {
return 100;
}
var newValue = func3(100);
alert(newValue);
First of all let breaks down the code. I write a function that expected as parameter a function and it will return a function.
function func1(func) {
return function(summand) {
return func() + summand;
}
}
Then i defined the parameter function func2 in expression form
var func2 = function() {
return 3;
}
then call func1 and give func2 as pamerater. As result i have got a function back
var func3 = func1(func2);
then i execute function and pass 4 as parameter argument
var value = func3(4);
as result i've got 7. Then i overwrite func2 and return 100
var func2 = function() {
return 100;
}
then call func3 again and pass as parameter value 100.
var newValue = func3(100);
as result i've got 103. The first function that i defined(that return a function and takes function as parameter), will still used the first version of func2. This the power of closure, i know it.
But look at the following code, when i define func2 as function declaration not as expression, then func2 will overwrite
function func1(func) {
return function(summand) {
return func() + summand;
}
}
function func2() {
return 3;
}
var func3 = func1(func2);
var value = func3(4);
alert(value);
function func2() {
return 100;
}
var newValue = func3(100);
alert(newValue);
The first value is 104 and second is 200.
My question is, why when i use function declaration it will overwrite the old function, in this example is func2. But when i use function expression it will keep the reference to old func2.
It that because of function hoisting?