Function.apply
can only be used to apply an array-like object1 to a function call. There is no equivalent to Pythons "keyword argument expansion" and this must be done manually:
var opts = {
dos: 'foo',
tres: 'bar',
uno: 'baz'
}
doSomething(opts.uno, opts.dos, opts.tres)
If we started with an array-like object:
var arr = ['baz', 'foo', 'bar']
doSomething.apply(window, arr)
Or putting the two together (so that the composition of to a parameter sequence can be handled earlier):
var arr = [opts.uno, opts.dos, opts.tres]
doSomething.apply(window, arr)
While it may be possible (with non-obfuscated code) to use Function.toString
2 to extract the parameter names, do some parsing, and then write some code to "apply" a general object (or construct an array that is then applied), this is not supported directly by the ECMAScript specification.
1 An array-like object is one that has a length
and properties named 0..length-1
. (Old versions of FF had a bug, but that has been fixed for a long time.)
2 The wording of the specification ("An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration..") makes me believe that a conforming ES5 implementation ought to produce output usable for this purpose - however, this will likely vary by implementation and I have not explored such usage in practice.