Javascript Closure


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.