Question

Consider this example, i need to know the benefits of using a high-order function as so:

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

I mean what's the problem with a simple function like so:

function bind(func, object) {
  return func.apply(object, arguments);
}
Was it helpful?

Solution 2

The benefit in your example is that you get partial application:

Intuitively, partial function application says "if you fix the first arguments of the function, you get a function of the remaining arguments". For example, if function div stands for the division operation x / y, then div with the parameter x fixed at 1 (i.e. div 1) is another function: the same as the function inv that returns the multiplicative inverse of its argument, defined by inv(y) = 1 / y.

The practical motivation for partial application is that very often the functions obtained by supplying some but not all of the arguments to a function are useful; for example, many languages have a function or operator similar to plus_one. Partial application makes it easy to define these functions, for example by creating a function that represents the addition operator with 1 bound as its first argument.

In your example, there's three pieces of information:

  1. which object
  2. which method to call
  3. which arguments to supply to that method call

Using your bind, you can decide on 1 and 2, while leaving 3 for later.

See Underscore for another example that generalizes partial application beyond just this.

OTHER TIPS

This

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

returns a result of func invocation. While bind should return a new function, which when called will be invoked in proper context (object).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top