Return to Snippet

Revision: 4375
at December 2, 2007 17:04 by 1man


Initial Code
/*
 * 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

Initial URL

                                

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

Initial Title
Javascript Closure

Initial Tags
javascript, function

Initial Language
JavaScript