2

I need a way to add extra parameters to callback method that should have a specific signature given by some service's API documentation.

For example, the callback should have one parameter of type string but I want to add an extra int to the parameters.

The only trick I thought of is abusing the "bind" like this:

var callbackFunc = originalCallback.bind({extraParam: myInt}, theNeededString)

And inside the callback I can get the int like this: this.extraParam

Do you have other tips or tricks?

Cel Skeggs
  • 1,827
  • 21
  • 38
Loves2Develop
  • 774
  • 1
  • 8
  • 29
  • What are you going to do with that extra param in the callback function? It seems to be a bit meaningless since the callback function can refer to any variables of the parent context. Just declare that extra param in the "parent" function that creates the callback. Example: var a = 10; var callback = function(str) {console.log(a);}; a = 20; callback(); - it will log 20. – Oleg K. Mar 31 '15 at 21:36

2 Answers2

1
var callbackFunc = function(theNeededString) { 
   originalCallbackind(theNeededString, myInt); 
};
Igor
  • 15,833
  • 1
  • 27
  • 32
  • To be more clear, what @Igor means is that you can reference variables in an *outer scope* (like the function that defines the callback) from an *inner scope* (like the callback itself.) – Cel Skeggs Apr 01 '15 at 01:24
  • Also, see this question for more information: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Cel Skeggs Apr 01 '15 at 01:25
-1

you can use the arguments object inside the function to get the extra params

function test(a){

    for(var i = 0; i<= arguments.length-1; i++) { 
        console.log(arguments[i])
    }
}

test(1,3,4,5)
 1
 3
 4
 5

i hope it can help you