What is fn.bind.apply(fn, arguments) doing?

1.7k views Asked by At

I saw this shortcut given as an answer on a code Kata but I am having difficulty understanding exactly what the below example is doing.

function func(fn) {
  return fn.bind.apply(fn, arguments);
}

So far my understanding is that bind creates a new function similar to doing the following:

function func(fn) {
  return function () {
    return fn.apply(fn, arguments);
  };
}

Is this the case? Any clearer answers or breakdowns of what is going on would be great.

1

There are 1 answers

3
Denys Séguret On BEST ANSWER
fn.bind

is just

Function.prototype.bind

So we're applying bind to fn, returning

fn.bind(arguments[0]/* doesn't matter, it's fn*/, arguments[1], arguments[2], etc.)

So the bound function is called with arguments being the arguments of func after fn.

Another way to write it would have been:

function func(fn) {
  var args = [].slice.call(arguments, 1);
  return function () {
    var localArgs = [].slice.call(arguments);
    return fn.apply(fn, args.concat(localArgs)); 
  };
}

The fact that the context of the call is the initial function (arguments[0]) is most certainly only a side effect. The important thing is we wrap the arguments with the function, but make it possible to dynamically pass other arguments.

Example 1, wrapping all arguments :

function add(a,b){
  return a+b
}
var f = func(add, 2 ,3); // f is a function which will always apply add to 2 and 3 
console.log(f()) // logs 5

Exemple 2, currying:

function multiply(a,b){
  return a*b
}
var multBy2  = func(multiply, 2);
console.log(multBy2(3)) // logs 6