/ Published in: JavaScript
Apologies if I haven't explained this to well, I'm still trying to get my head round closures.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* * Since we are passing the inner function outside, a reference to it * still exists, hence it is not collected by the garbage collector. * * The variable a persists through to the next increment, and is not overwritten * by outer() var a = 0 since inner still has a local variable inside it's scope. * * By creating global2, you have created another scope that acts independently, * even though they are using the same function literal! */ function outer(){//define outer scope var a = 0;//this is the persistent variable function inner(){//define the inner scope a++;//increment a console.log(a); } return inner;//IMPORTANT: return the inner function to the outside (scope) } var global = outer();//create a new scope in global global();//a = 1 global();//a = 2 var global2 = outer(); global2();//a = 1 global2();//a = 2