Javascript function as a parameter to another function?

后端 未结 7 1100
执念已碎
执念已碎 2021-01-31 06:17

I\'m learning lots of javascript these days, and one of the things I\'m not quite understanding is passing functions as parameters to other functions. I get the concept

7条回答
  •  爱一瞬间的悲伤
    2021-01-31 06:35

    You would do this if callerFunction wants to call doStuff later, or if it wants to call it several times.

    The typical example of this usage is a callback function, where you pass a callback to a function like jQuery.ajax, which will then call your callback when something finishes (such as an AJAX request)

    EDIT: To answer your comment:

    function callFiveTimes(func) {
        for(var i = 0; i < 5; i++) {
            func(i);
        }
    }
    
    callFiveTimes(alert);  //Alerts numbers 0 through 4
    

提交回复
热议问题