How to execute a method passed as parameter to function

前端 未结 8 621
旧巷少年郎
旧巷少年郎 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.

    0 讨论(0)
  • 2020-12-13 04:18

    I will do something like this

    var callbackfunction = function(param1, param2){
    console.log(param1 + ' ' + param2)
    }
    
    myfunction = function(_function, _params){
    _function(_params['firstParam'], _params['secondParam']);
    }
    

    Into the main code block, It is possible pass parameters

    myfunction(callbackfunction, {firstParam: 'hello', secondParam: 'good bye'});
    
    0 讨论(0)
提交回复
热议问题