[removed] Passing parameters to a callback function

后端 未结 13 2168
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 15:48

I\'m trying to pass some parameter to a function used as callback, how can I do that?

function tryMe (param1, param2) {
    alert (param1 + \" and \" + param         


        
13条回答
  •  死守一世寂寞
    2020-11-22 16:11

    Code from a question with any number of parameters and a callback context:

    function SomeFunction(name) {
        this.name = name;
    }
    function tryMe(param1, param2) {
        console.log(this.name + ":  " + param1 + " and " + param2);
    }
    function tryMeMore(param1, param2, param3) {
        console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
    }
    function callbackTester(callback, callbackContext) {
        callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
    }
    callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
    callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");
    
    // context1: hello and goodbye
    // context2: hello and goodbye and even hasta la vista
    

提交回复
热议问题