You could use apply
:
foo.apply(this, Array(5).concat([theFValue]));
In this case, 5
is the amount of parameters you want to skip.
Wrap that in a function:
function call(fn, skipParams, parameter) {
fn.apply(this, Array(skipParams).concat([parameter]));
}
call(foo, 5, theFValue);
However, in that case the scope of this
is different, so you may need to pass that, too:
function call(fn, skipParams, parameter, thisArg) {
fn.apply(thisArg, Array(skipParams).concat([parameter]));
}
call(foo, 5, theFValue, this);
Then again, this implementation only allows 1 parameter to be passed. Let's improve that:
function call(fn, skipParams, parameters, thisArg) {
fn.apply(thisArg, Array(skipParams).concat(parameters));
}
call(foo, 5, [theFValue, theGValue, theHValue], this);
That's starting to get a "little" verbose. It also doesn't handle missing parameters after the first parameter that well, unless you want to pass undefined
:
call(foo, 5, [theFValue, theGValue, theHValue, undefined, theJValue], this);
Or, something completely different:
var _ = undefined;
foo(_,_,_,_,_, theFValue);
On a more serious note:
Your best option to deal with optional parameters, is to change the way you're handling parameters. Simply pass an object:
function foo(parameters){
// do stuff with `parameters.a`, `parameters.b`, etc.
}
foo({c: 1, g: false});
This approach doesn't suffer from any of the drawbacks in the earlier examples.