How can I call Function.prototype.bind with an array of arguments, as opposed to hardcoded arguments? (Not using ECMA6, so no spread operator).
I\'m trying to put a
Generically, this schema suffices:
//obj = db
//fnName = 'find'
var args = [this||null].concat(Array.prototype.slice.apply(arguments);
obj[fnName].bind.apply(obj[fnName], args);
For those using ES6, Babel compiles:
db.find.bind(this, ...arguments)
to:
db.find.bind.apply(db.find, [this].concat(Array.prototype.slice.call(arguments)));
I think it's fair to say Babel is pretty definitive. Credit to @lorenz-lo-sauer though, it's almost identical.
Just had an alternative idea, partially apply the null
value for context and then use apply
to call the partially applied function.
bound = db.find.bind.bind(null).apply(null, arguments);
This removes the need for the slightly spooky looking [null].concat()
in @Felix's answer.
I find following cleaner than the accepted answers
Function.bind.apply(db.find, [null].concat(arguments));