callback function meaning

后端 未结 4 761
梦谈多话
梦谈多话 2020-12-03 06:06

What is the meaning of callback function in javascript.

4条回答
  •  情深已故
    2020-12-03 06:46

    JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call...

    Main function can look like this:

    function mainFunc(callBack)
    {
        alert("After you click ok, I'll call your callBack");
    
        //Now lets call the CallBack function
        callBack();
    }
    

    You will call it like this:

    mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}
    

    Or:

    function thisIsCallback()
    {
        alert("LALALALALALA ITS CALLBACK!");
    }
    
    mainFunc(thisIsCallback);
    

    This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends.

    Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call (calBack()) totally depends on that function's implementation.

    Even the name "call-back" is self-explanatory... =)

提交回复
热议问题