Basically I am wondering when it is necessary to use
function(){ ... }
(without a name) and when to use functionfunction_name(){ ... }
(with a name)
It is never really necessary to use either. It is just sometimes more convenient to use one or the other.
and how to execute a function with things like .click() .post() or setTimeout().
If you are using the function that accepts the callback, then you just pass the function you want to use as the callback like any other variable or literal.
If you want to write a function that uses a callback, then it essentially boils down to:
function accepts_callback(callback) {
callback();
}
function a_callback() {
alert("This is a callback");
}
accepts_callback(a_callback);
you can't just say
.click( function_name() )
Putting ()
after a function will call it. Don't include them as you can pass it.
Why will this script alert first five,
The first thing you do, other then declare functions, is make a function call: var alert_five = alert_five();
then two
$('#two').click( alert('two') );
//this will alert two right away, because...?
You are calling alert
here
//it wont do anything else on click
The return value of alert
will always be undefined
, which isn't a function
then three on startup?
$('#three').click( alert_three() );
//this will alert three right away, because...?
You are calling the alert_three
function immediately.
//it wont do anything else on click
alert_three
has no return statement, so it returns undefined
, which isn't a function
Why will only buttons 1, 4, 6, and 7 work correcty?
The are the only ones for which you give a function as the argument to click()
.