15

I perfectly know the usages for :

Function.prototype.bind.apply(f,arguments)

Explanation - Use the original (if exists) bind method over f with arguments (which its first item will be used as context to this)

This code can be used ( for example) for creating new functions via constructor function with arguments

Example :

function newCall(Cls) {
    return new (Function.prototype.bind.apply(Cls, arguments));
 }

Execution:

var s = newCall(Something, a, b, c);

But I came across this one : Function.prototype.apply.bind(f,arguments) //word swap

Question :

As it is hard to understand its meaning - in what usages/scenario would I use this code ?

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • You can use `apply` if you don't care about `this` and do not want to create an anonymous function (with `bind`). – Florent Mar 11 '14 at 09:51
  • Related - http://stackoverflow.com/questions/10247807/avoiding-call-and-apply-using-bind – Achrome Mar 11 '14 at 09:59

1 Answers1

31

This is used to fix the first parameter of .apply.

For example, when you get the max value from an array, you do:

var max_value = Math.max.apply(null, [1,2,3]);

But you want to get the first parameter fixed to null, so you could create an new function by:

var max = Function.prototype.apply.bind(Math.max, null);

then you could just do:

var max_value = max([1,2,3]);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 4
    **very** nice example – Royi Namir Mar 11 '14 at 10:02
  • 3
    Why it's important to pass null for bind as argument? – sAs59 Mar 13 '18 at 20:23
  • @sAs59 It's to give permanent null parameter on first parameter of `generated Math.max.apply` for `max` variable. When following gets called for example: `max([1,2,3])`. That calls `Math.max.apply(null, [1,2,3])`. Whereas with `Function.prototype.apply.bind(Math.max)`, The generated code for `max([1,2,3])` is just simply `Math.max.apply([1,2,3])`, which would give incorrect result. The first parameter of Math.max.apply will be assigned to `this` reference, the second parameter (an array) would get passed to the actual parameters of the function. Without null, the `[1,2,3]` goes to `this`. – Michael Buen May 27 '20 at 15:48
  • @sAs59 Then the actual parameters for Math.max would receive nothing. – Michael Buen May 27 '20 at 15:50