Callback function - use of parentheses

后端 未结 4 1871
滥情空心
滥情空心 2020-12-03 08:21

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 somethin         


        
相关标签:
4条回答
  • 2020-12-03 08:43

    $("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);

    0 讨论(0)
  • 2020-12-03 08:46

    cb() means give me the result of executing the function cb.

    cb IS the function cb or, more accurately a pointer (reference) to it.

    0 讨论(0)
  • 2020-12-03 08:48

    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
    
    0 讨论(0)
  • 2020-12-03 08:54

    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.

    0 讨论(0)
提交回复
热议问题