do I need parenthesis when using a named function as an jquery ajax success callback

if I have a function defined earlier, do I need to include parenthesis when specifying that it should be used for a success callback?

what would be the difference if I did?

as in

function fish_food(){//do something}

$.ajax({
    url: '/',
    success: fish_food
});

or

$.ajax({
    url: '/',
    success: fish_food()
});

Answers:

Answer

fish_food on its own (without parens) acts as a reference to the function object. It allows you to pass the reference to the function around to be invoked at some later date.

fish_food() (with parens) is a function invocation expression, which causes the function to be executed. The function code is evaluated and run with a value optionally being returned.

With the AJAX code you supplied (and all async JavaScript involving callbacks) you want to use the fish_food version (without parens). This passes the AJAX code a reference to your success function, to be executed asynchronously once the AJAX code has completed its round trip to the server and back.

Answer

No.

Parentheses will tell the browser that function fish_food needs to be executed immediately, and the value has to be returned to a success property.

Answer

You want the no-parens version. The reason is that the parentheses tell JavaScript to execute the function right away, rather than just reference it by name, so your success callback would actually be the results of invoking fish_food() whenever you are executing the AJAX call (which is probably going to be an error involving undefined).

Answer

this will work

$.ajax({
    url: '/',
    success: fish_food
});
Answer

You don't need the parenthesis. Using parens would invoke the function, what it needs is just a name which is equivalent to function pointers in C/C++.

Answer

Having the parenthesis causes the function to execute then and there, that is why you need first version else success stores return value of the function.

Answer
$.ajax({
    url: '/',
    success: fish_food
});

is correct.

When you use success: fish_food(), it will be executed right away and the return is set to success.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.