I'm new to jQuery and am bit confused about the use (or not) of parentheses with a callback function. Say I have a function:
function cb() {
// do something
}
Now what is the difference betw开发者_开发知识库een:
$("p").hide(1000, cb);
and
$("p").hide(1000, cb());
Is it to do with when the cb function is executed? It would be great if someone could explain this to me in the simplest of terms.
cb()
means give me the result of executing the function cb.
cb
IS the function cb or, more accurately a pointer (reference) to it.
Is it to do with when the cb function is executed?
Essentially, yes, though the difference does run a little deeper than that.
cb
is a reference of sorts to the function. You're passing the function along as a parameter to be invoked somewhere down the line.cb()
is a function call; the function will be invoked, and the result passed as an argument to.hide
.
The difference is that in javascript functions are first class objects and can be passed to other functions so that they may executed at a later stage or depending on some logic.
Consider the following:
function add(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function apply(func, a, b) {
return func(a,b);
}
apply(add, 3, 4); // returns 7
apply(minus, 3, 4); // returns -1
apply(add(), 3, 4); // error: invalid number of arguments for add
apply(add(0,0), 3, 4); // error: add returns 0, but 0 is not a function and
// so apply crashes when it tried to call zero as a function
$("p").hide(1000, cb);
passes the function referenced by cb
, as a callback.
$("p").hide(1000, cb());
passes the value returned when the function cb
is called.
Given:
function cb(){ return true; }
The former is passing the callback for later calling. The latter passes the returned value true
, and is essentially $("p").hide(1000, true);
精彩评论