如果我有一个函数定义的前面,做我需要包括指定它应该用于一个成功的回调时,括号?
会有什么区别,如果我这样做?
在
函数fish_food(){//做一些事情}
$阿贾克斯({
网址:'/',
成功:fish_food
});
或
$。阿贾克斯({
网址:'/',
成功:fish_food()
});
解决方案
fish_food
自己(不含括号)作为一个参考函数对象。它可以让你引用传递给周围的一些日后调用的函数。
fish_food()
(带括号)是一个函数调用前pression,这导致被执行的功能。该函数code进行评估并运行任意返回一个值。
通过您所提供的AJAX code(以及所有异步的JavaScript涉及回调)要使用 fish_food
(不带括号)。这传递了AJAX codeA引用你的成功的功能,异步执行,一旦AJAX code已经完成了往返于服务器和背部。
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. 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.