Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Why does this work…
$("#clickme").click( showAlert );
function showAlert() {
alert( "Hiya" );
}
… but not this…?
$("#clickme").click( showAlert );
var showAlert = function() {
alert( "Hello" );
}
This is happening due to hoisting.
In your first case, the code is interpreted as (notice how the function declaration is being evaluated first):
And your second is interpreted as :
Since
showAlertis a variable declaration and not a function declaration (notice thevarkeyword), the variable declaration is evaluated first, and by the time you bind the event handler, theshowAlertvariable is declared, but it holds theundefinedvalue.This is what hoisting does : it hoists variable and function declarations to the top of the closure.
There are a couple of good resources on hositing out there, including here on SO.