I have a custom object that implements a function that’ll be executed later. Here’s how someone would call it:
customObject.onSomething(function(e) {
// do something with e
console.log('foobar');
});
Here’s how onSomething is getting created:
var CustomObject = function() {
this.onSomething = function(callback) {
// If the user passes in parameter(s), how can I modify them before calling?
callback.apply(this);
}
}
How can I modify the argument(s) the user passed in before performing apply or call on the function?
applytakes a second parameter which is a list of arguments to pass to the function.calldoes the same, except it passes its own argument-list (everything after the first parameter which is used asthis).So, if you know which parameters you expect, you can just add them to the invoking function as the second parameter to
apply(or as a list of parameters tocall):If you don’t know what kind of arguments to expect, but you still want to do something with them, you can do so with the builtin
argumentspseudo-array which holds the arguments given to the current function (even when you don’t declare them explicitly).You can use this to invoke the callback with the same arguments given to the invoking function, or some transformation of them; e.g.: