Posted By

1man on 12/02/07


Tagged

javascript function closure return inner


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tkabbs


Javascript Closure


 / Published in: JavaScript
 

Apologies if I haven't explained this to well, I'm still trying to get my head round closures.

  1. /*
  2.  * Since we are passing the inner function outside, a reference to it
  3.  * still exists, hence it is not collected by the garbage collector.
  4.  *
  5.  * The variable a persists through to the next increment, and is not overwritten
  6.  * by outer() var a = 0 since inner still has a local variable inside it's scope.
  7.  *
  8.  * By creating global2, you have created another scope that acts independently,
  9.  * even though they are using the same function literal!
  10.  */
  11. function outer(){//define outer scope
  12. var a = 0;//this is the persistent variable
  13. function inner(){//define the inner scope
  14. a++;//increment a
  15. console.log(a);
  16. }
  17. return inner;//IMPORTANT: return the inner function to the outside (scope)
  18. }
  19. var global = outer();//create a new scope in global
  20. global();//a = 1
  21. global();//a = 2
  22. var global2 = outer();
  23. global2();//a = 1
  24. global2();//a = 2

Report this snippet  

You need to login to post a comment.