3

From what i understand, in jquery, when a method requires a function as an argument you can't just invoke a predefined function like this:

$('#target').click(myFunction());

...because "myFunction()" will be parsed and replaced with the value returned by the function...which is no longer a function.You have to put the entire function definition, in an anonymous function:

$('#target').click(function() {
   alert('Handler for .click() called.');
});

...so, is there any way of just invoking the function where it's required as an argument?

2 Answers 2

4

You understand correctly. It is true not only in jQuery, this is how JavaScript works. When a function is needed as an argument, then you have to give a function as an argument, and not the result of its invocation. You can use this:

$('#target').click(myFunction);

but for alert you need an anonymous function because you are passing an argument.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 Addendum: Functions in JavaScript are just objects that can be applied [read: invoked] with the () operator. That is, fn() evaluates the expression fn to the function-object (say fn is fn = function () { ... } or function fn () { ... }) and then the () operator invokes the function-object and the value of the expression is the result of that invocation [read: what was return'ed]. Thus, without the () operator, the name of a function evaluates to the function-object itself. (This is a good bit different than how Java/C/C++/C# (or even Ruby) work but similar to Python.)
thanks...so you can't invoke it with arguments: $('#target').click(myFunction(arg1, arg2)); ?
@bogdan You can -- but that passes the result of myFunction(arg1, arg2) as the value to click [see ()]. This is case for a closure: elm.click(function () { myFunction(arg1, arg2) }), where arg1 and arg2 are free variables in the enclosing scope. Note that the function-object returned by function () { ... } is not evaluated (applied/invoked), but rather passed as the argument to click -- click will invoke the function-object passed in later when an event occurs and that (anonymous) function object invokes myFunction with the given variables (hopefully) bound in a closure.
@pst Thank you for the in depth explanation :)
2

You are passing the result of the function, not the function itself. Instead of:

click(myFunction());

use

click(myFunction);

Live example on jsfiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.