Using Function.prototype.bind with an array of arguments?

后端 未结 10 1850
春和景丽
春和景丽 2020-12-08 01:57

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

相关标签:
10条回答
  • 2020-12-08 02:47

    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);
    
    0 讨论(0)
  • 2020-12-08 02:48

    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.

    0 讨论(0)
  • 2020-12-08 02:49

    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.

    0 讨论(0)
  • 2020-12-08 02:50

    I find following cleaner than the accepted answers

    Function.bind.apply(db.find, [null].concat(arguments));
    
    0 讨论(0)
提交回复
热议问题