6

Some jQuery methods expect a function as a parameter, but to work they should receive an anonymous function as a parameter rather than a function directly, as in the following example:

$("a").on("click", function () { retornaNada(); }); 

rather than

 $("a").on("click", retornaNada());

Consider retornaNada() as a function without any body of code. Why can not we pass the function directly?

7
  • 1
    You need to pass them a reference to a function, not an "inner function". So, you'd do .on("click", retornaNada);. Commented Feb 3, 2014 at 16:05
  • 4
    not sure why the down votes... this person clearly is new to javascript and doesn't understand the way it works Commented Feb 3, 2014 at 16:06
  • The one that downvoted could, please, tell why? Commented Feb 3, 2014 at 16:06
  • Also, some functions require access to parameters in the scope they were created, so closures are used: learn.jquery.com/javascript-101/closures Commented Feb 3, 2014 at 16:06
  • 3
    The code examples are both hideously broken with mismatched parenthesis, stray periods and apostrophes. Commented Feb 3, 2014 at 16:07

1 Answer 1

5

It's working but you need to pass only the function reference (name) like this :

function test (e) {
    console.log('test ok');
}
$('body').on('click', test);
Sign up to request clarification or add additional context in comments.

7 Comments

Change this to say "pass a reference to a function" rather than "pass only the function name". What you said it true, but it's not complete.
name isn't always the reference. function (e) { // } is also a reference that isn't passed by name. That's the point I was trying to get across.
Another way to say this is "pass the function, not the result." Unless the function result is itself a function, of course.
Obviously the guy is a new to JS, it's more clear to him explained in less technical terms. If it's a reference, closure, or who cares what else he really won't care until he understands the basics of the error..
@Goran.it You should always give a complete example, that introduces the OP to technical terminology. This isn't an attack on your answer. It's a plead to improve it. Mention that referring to the function by name is one form of referencing the function. Then, show him that it is equivalent to passing an anonymous function, which is also a function reference.
|

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.