views:

24

answers:

3

why do I have to do this:

$('#myfoo').change(function(){mylongfunc();});

instead of this:

$('#myfoo').change(mylongfunc());

what does that extra function(){} wrapper do?

+2  A: 

You don't need the wrapper function, just a little tweak to your approach, like this:

$('#myfoo').change(mylongfunc);

The function() {} is just an anonymous function, you can use a named function directly like you want, just pass the function.

mylongfunc //passes the function
mylongfunc() //passes the RESULT of the function
Nick Craver
A: 

There is a subtle difference.

When you do function(){ myLongFunc(); } you're defining an anonymous function that is a wrapper around myLongFunc.

When you do change(myLongFunc()) you don't get the result you expect, because that actually calls the function and passes the result of the call to change.

So what you actually want to do is change(myLongFunc) because now you're passing in the actual function object.

There is another scenario:

var myLongFunc = function() { ... };

Now when you pass in myLongFunc, you're passing in a reference to an anonymous function.

Another form that Javascript functions take is the function literal, where you define a function and call it immediately. This works because functions are first-class objects in Javascript:

(function() {
 ...
})();

or even:

(function myFunc() {
 ...
})();

In this scenario, you are defining the function and calling it immediately. This form is usually used for namespacing and encapsulation when creating frameworks or libraries. jQuery does this and it is called the module pattern.

Vivin Paliath
A: 

This uses an "anonymous" function.

$('#myfoo').change(function(){mylongfunc();});

This uses a pre-defined, reusable function. Note: I removed the () from mylongfunc

$('#myfoo').change(mylongfunc);

The basic rule is this:

Use anonymous functions when they're only going to be used once.

Use regular functions when they're going to be used more than once (or shared by other code).

macek