Closure Example
by savid
JavaScript
var getNameMaker = function(last, first) {
var fullName = first + ' ' + last;
// because we're defining a function within a function, we're creating a closure.
// the closure contains the variables we've defined in getNameDescriber
return function(){ alert(fullName); }
}
var sayName = getNameMaker('Doe', 'John');
// sayName is now a reference to the function defined within getNameMaker
alert(sayName.toString());
// The reason this works is because sayName has with it a reference to the closure
// created within getNameMaker. The fullName variable still exists even after
// getNameMaker exits.
sayName();