How to pass a callback as a parameter into another function

后端 未结 6 1716
生来不讨喜
生来不讨喜 2020-11-28 03:32

I\'m new to ajax and callback functions, please forgive me if i get the concepts all wrong.

Problem: Could i send a callbackfunction

6条回答
  •  旧巷少年郎
    2020-11-28 04:07

    Yup. Function references are just like any other object reference, you can pass them around to your heart's content.

    Here's a more concrete example:

    function foo() {
        console.log("Hello from foo!");
    }
    
    function caller(f) {
        // Call the given function
        f();
    }
    
    function indirectCaller(f) {
        // Call `caller`, who will in turn call `f`
        caller(f);
    }
    
    // Do it
    indirectCaller(foo); // alerts "Hello from foo!"

    You can also pass in arguments for foo:

    function foo(a, b) {
        console.log(a + " + " + b + " = " + (a + b));
    }
    
    function caller(f, v1, v2) {
        // Call the given function
        f(v1, v2);
    }
    
    function indirectCaller(f, v1, v2) {
        // Call `caller`, who will in turn call `f`
        caller(f, v1, v2);
    }
    
    // Do it
    indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3"

提交回复
热议问题