简体   繁体   English

将命名函数用作jQuery ajax成功回调时需要括号吗?

[英]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()
});

fish_food on its own (without parens) acts as a reference to the function object. fish_food本身(不带括号)充当对功能对象的引用。 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. fish_food() (带括号)是一个函数调用表达式,它使函数被执行。 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). 使用您提供的AJAX代码(以及涉及回调的所有异步JavaScript),您想使用fish_food版本(不带括号)。 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. 这会将AJAX代码传递给您的成功功能参考,一旦AJAX代码完成了往返服务器的往返行程,就将异步执行该代码。

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. 括号会告诉浏览器,必须立即执行函数fish_food ,并且必须将值返回给success属性。

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 ). 原因是括号告诉JavaScript立即执行该函数,而不是仅按名称引用它,因此, success回调实际上是在执行AJAX调用时调用fish_food()的结果(可能会是涉及undefined的错误)。

this will work 这会工作

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

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++. 使用parens将调用该函数,它所需要的只是一个名称,该名称等效于C / C ++中的函数指针。

带有括号会导致函数在那儿执行,这就是为什么需要第一个版本,否则成功存储函数的返回值的原因。

$.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. 当您使用success: fish_food() ,它将立即执行并将返回值设置为成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM