Reputation: 1574
In trying to grasp some fundamentals of jQuery and JavaScript at the same time, I'm a little confused as to why jQuery takes an anonymous function as an argument. Like this:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
as opposed to this:
$( "#target" ).click(alert("You clicked it."));
In jQuery's own "101" guide, they point out that "Passing functions as arguments is an extremely common idiom in jQuery." But they don't seem to explain why. Is it just to provide a wrapper for a block of expressions, or (I suspect) much more than that?
Upvotes: 1
Views: 1220
Reputation: 29658
To answer your specific question, the reason is because this code:
$( "#target" ).click(alert("You clicked it.");
does the following:
alert
with "You clicked it."
as parameteralert
call (which is undefined
) as a click handler for #target
.In other words, alert
is called immediately and undefined
is bound as the event handler, which makes no sense.
Whereas with the first code snippet:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
alert( "Handler for .click() called." );
]For more information of anonymous functions, see this question.
Upvotes: 5
Reputation: 28688
Well, passing functions as arguments is an extremely common idiom in JavaScript. Sometimes you need to pass a callback function to another function, for example an event handler, and you don't need to define it separately and give it a name. If you need to call that function somewhere else too, then you define it separately with its own name, but if you need it only in one place, then there is no need to give it a name.
Upvotes: 1
Reputation: 55962
the first param to click
is a callback function. A callback function is executed after the click event.
Functions in javascript are first class objects. This means they can be passed as parameters. You could pass alert
to the click
method. But in your second example you are not passing it, you are calling it (see Doorknob's answer)!
Upvotes: 1
Reputation: 59283
In your second example, it would actually call click with undefined
. Try it:
> alert
function alert() { [native code] }
> alert('test')
undefined
This is because the alert
function returns undefined
, so you're actually calling the method with undefined
as the argument.
Is it just to provide a wrapper for a block of expressions
Well, how else would you do it? The only way to express "a block of expressions" in JavaScript is... you guessed it: functions.
Upvotes: 1