Gregir
Gregir

Reputation: 1574

jQuery: Why use anonymous functions as argument?

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

Answers (4)

Chris Laplante
Chris Laplante

Reputation: 29658

To answer your specific question, the reason is because this code:

$( "#target" ).click(alert("You clicked it.");

does the following:

  1. Calls alert with "You clicked it." as parameter
  2. Binds the result of that alert 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." );
});
  1. An anonymous function is created [ alert( "Handler for .click() called." ); ]
  2. And the result of that expression (a function) is bound as an event handler

For more information of anonymous functions, see this question.

Upvotes: 5

kol
kol

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

dm03514
dm03514

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

tckmn
tckmn

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

Related Questions