19

Javascript code:

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

function SomeClass(callbackFunction,callbackFuncParameters(*Array*))={
   this.callback = callbackFunction;
   this.method = function(){
       this.callback(parameters[0],parameters[1])  // *.*
   }
}

var obj = new SomeClass( doSomething, Array('v1text','v2text') );

The problem is if I change function doSomething to

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

I have to change the corresponding line (marked as //*.*) in SomeClass to

this.callback(parameters[0],parameters[1],parameters[2]);

What can be done to avoid the (*.*) line to be changed no matter how the number of 'doSomething' function's parameters is changed?

Thanks a lot!

Shawn
  • 32,509
  • 17
  • 45
  • 74

2 Answers2

25

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.

krosenvold
  • 75,535
  • 32
  • 152
  • 208
  • 1
    Im a little confused on how to use this functionality. What I want to do is pass a function to a callback like this - myfunction(function(myele) { //use myele }). So I am passing an anon callback function here with the myele parameter being passed to it. How would I do this with your code above? – Metropolis Aug 24 '10 at 21:33
  • https://jsfiddle.net/osyzc1d4/3/ – Harshil Modi Jan 31 '22 at 09:49
2

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"}
Marcus
  • 3,459
  • 1
  • 26
  • 25