Closure fiddle
From http://javascriptissexy.com/understand-javascript-closures-with-ease/
by michiecat
HTML
This is one of the examples from http://javascriptissexy.com/understand-javascript-closures-with-ease/
I didn't write this script. I'm studying it to understand closures.
JavaScript
function celebrityName(firstName) {
var nameIntro = "This celebrity is ";
// this inner function has access to the outer function's variables, including the parameter
function lastName(theLastName) {
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}
var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.
// The closure (lastName) is called here after the outer function has returned above
// Yet, the closure still has access to the outer function's variables and parameter
mjName("Jackson"); // This celebrity is Michael Jackson
alert(mjName("Jackson"));