Let’s say I have a function:
function myFunction() {
...
}
I want to call it from event handler. Why this construction doesn’t call my function?
$(window).resize(myFunction());
But this does the trick:
$(window).resize(function(){myFunction()});
What is the difference between these types of calling?
immediately calls
myFunctionand passes the return value toresize. Adding parenthesis after a function name/reference calls the function.On the other hand,
passes an anonymous function to
resize.myFunctionis only called when the outer function is called.Anonymous functions are nothing special. In this case it is just some kind of inline function definition. You can easily replace it with a function reference:
Now you can see that there are no parenthesis after the function name, which means,
handleris not called, only the reference is passed.I hope you can also see now that creating a new function in this example is not necessary. You can achieve the same by simply passing a reference to
myFunction:But both ways have their use cases.
The first example
$(window).resize(myFunction());can still be useful ifmyFunctionreturns a function that should be used as event handler:Maybe the handler retuned depends on a parameter passed to
myFunction.Passing an anonymous function is necessary if you want to call
myFunctionwith some specific arguments:Update:
@T.J. Crowder made an important comment about the
eventobject. Every event handler gets the event object passed as first parameter. If you’d define your function asto have (easier) access to it, using an anonymous function, you would have to pass it through:
if you want to use it.