How to execute a method passed as parameter to function

前端 未结 8 649
旧巷少年郎
旧巷少年郎 2020-12-13 03:44

I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don\'t know how to invoke a method in my m

8条回答
  •  臣服心动
    2020-12-13 04:18

    You can just call it as a normal function:

    function myfunction(param1, callbackfunction)
    {
        //do processing here
        callbackfunction();
    }
    

    The only extra thing is to mention context. If you want to be able to use the this keyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:

    function myfunction(param1, callbackfunction)
    {
        //do processing here
        callbackfunction.call(param1);
    }
    

    In the callback, you can now access param1 as this. See Function.call.

提交回复
热议问题