Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

3 of 3
added 11 characters in body
Royi Namir
  • 149.3k
  • 145
  • 504
  • 833

Javascript Closure Clarification?

As many as Articles as i've read , I still have some questions.

I already know (and understand) the usages of closure like :

  1. The Infamous Loop Problem ( loop of links with alert on each one of them with kept number)

  2. 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)

  1. Make an outer, "function maker" function.
  2. Declare a local variable inside it.
  3. Declare an inner function inside the outer one.
  4. Use the outer function's variable inside the inner function.
  5. Have the outer function return the inner function
  6. 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.

Royi Namir
  • 149.3k
  • 145
  • 504
  • 833
lang-js

AltStyle によって変換されたページ (->オリジナル) /