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

后端 未结 10 1849
春和景丽
春和景丽 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:27

    The following is a common snippet of code I use in all my projects:

    var bind = Function.bind;
    var call = Function.call;
    
    var bindable = bind.bind(bind);
    var callable = bindable(call);
    

    The bindable function can now be used to pass an array to bind as follows:

    var bound = bindable(db.find, db).apply(null, arguments);
    

    In fact you can cache bindable(db.find, db) to speed up the binding as follows:

    var findable = bindable(db.find, db);
    var bound = findable.apply(null, arguments);
    

    You can use the findable function with or without an array of arguments:

    var bound = findable(1, 2, 3);
    

    Hope this helps.

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

    If someone is looking for an abstract sample:

    var binded = hello.apply.bind(hello,null,['hello','world']);
    
    binded();
    
    function hello(a,b){
      console.log(this); //null
      console.log(a); //hello
      console.log(b); //world
    }
    
    0 讨论(0)
  • 2020-12-08 02:35

    Why not simply bind to the arguments array as per your example, and have the bound() function treat it just like that, as an array?

    By the looks of your usage, you are then passing in a function as the final argument to bound(), which means by passing in the actual argument array, you avoid having to separate arguments from callbacks inside bound(), potentially making it easier to play with.

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

    A definitive and simple answer might be

    Function.apply.bind(this.method, this, arguments);
    

    Kinda "hard" to grasp, yet, neat.

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

    .bind is a normal function, so you can call .apply on it.
    All you have to do is pass the original function as the first param and the desired THIS variable as the first item in the array of arguments:

    bound = db.find.bind.apply(db.find, [null].concat(arguments));
    //      ^-----^            ^-----^   THIS
    

    Whether that can be considered cleaner or not is left to the reader.

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

    Felix's answer didn't work for me because the arguments object isn't really an array (as Otts pointed out). The solution for me was to simply switch bind and apply:

    bound = db.find.apply.bind(db.find, null, arguments);
    
    0 讨论(0)
提交回复
热议问题