As many as Articles as i've read , I still have some questions.
I already know (and understand) the usages of closure like :
The Infamous Loop Problem ( loop of links with alert on each one of them with kept number)
increased counter (keep calling a function -> which alerts increased numbers)
From here :
inner functions referring to local variables of its outer function create closures
From here :
a closure is the local variables for a function - kept alive after the function has returned, or a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
3 Questions please:
Question #1
I was told that all functions in JS create Closures.
WHAT ??? if I create a normal function with private variable it just create a scope. not closure.
I thought that closure work like this:(from here)
- Make an outer, "function maker" function.
- Declare a local variable inside it.
- Declare an inner function inside the outer one.
- Use the outer function's variable inside the inner function.
- Have the outer function return the inner function
- Run the function, and assign its return value to a variable
exmample:
function functionMaker(){
var x = 1;
function innerFunction(){
alert(x);
x++;
}
return innerFunction;
}
So why do they say that every js function create closure ?
Question #2
Does Self-Invoking Functions
aka IEFA - Immediately Invoked Function Expression
creates a closure ?
looking at
(function (a) {
alert(a);
})(4);
I don't see the pattern like the 6 rules from the above :
where exactly Have the outer function return the inner function
is here ? I dont see the word return
.
Question #3
function myFunction() {
var myVar = 1;
var alertMyVar = function () {
alert('My variable has the value ' + myVar);
};
setTimeout(alertMyVar, 1000 * 3600 * 24);
}
myFunction();
Does myFunction
was alive for the whole day here ? or it was ended as soon after the setTimeout
? and if so , how did SetTimeOut
remembered that value ?
Please help me to get it right.