How do I pass multiple arguments into a javascript callback function?

前端 未结 2 590
轻奢々
轻奢々 2021-02-04 03:38

Javascript code:

function doSomething(v1,v2){ //blah; }

function SomeClass(callbackFunction,callbackFuncParameters(*Array*))={
   this.callback = callbackFuncti         


        
相关标签:
2条回答
  • 2021-02-04 04:09

    Another way now available is to use spread syntax.

    this.callback(...callbackFuncParameters)
    

    Here it is again with the full example from the OP:

    function doSomething(v1,v2) {
        console.log('doing', {v1, v2});
    }
    
    function SomeClass(callbackFunction, callbackFuncParameters) {
       this.callback = callbackFunction;
       this.method = function(){
           this.callback(...callbackFuncParameters); // spread!
       }
    }
    
    var obj = new SomeClass( doSomething, Array('v1text','v2text') );
    obj.method()
    // output: doing {v1: "v1text", v2: "v2text"}
    
    0 讨论(0)
  • 2021-02-04 04:32

    You probably want to use the apply method

    this.callback.apply(this, parameters);
    

    The first parameter to apply indicates the value of "this" within the callback and can be set to any value.

    0 讨论(0)
提交回复
热议问题