How can I pass a reference to a function, with parameters?

Andreas Grech picture Andreas Grech · Dec 17, 2008 · Viewed 110.7k times · Source

Possible Duplicate:
How can I pre-set arguments in JavaScript function call? (Partial Function Application)

I need to able to pass a reference to a function with a given set of parameters.

Here is an example of passing a reference without parameters:

var f = function () {
    //Some logic here...
};

var fr = f; //Here I am passing a reference to function 'f', without parameters
fr(); //the 'f' function is invoked, without parameters

Now what I need to do is pass the same f function, but this time I would need to pass parameters to the reference. Now, I can do it with an anonymous function and invoke the f function with parameters inside the newly created function, like such:

var f = function () {
        //Some logic here...
    };

var fr = function (pars) {
    f(pars);
}; //Here I am creating an anonymous function, and invoking f inside it

fr({p : 'a parameter'}); //Invoking the fr function, that will later invoke the f function with parameters

But my question is, Is there a way to pass a direct reference to the f function With parameters to fr, but without enclosing it in an anonymous function?

What do I need to assign to fr to make it invokable without parameters (fr()), so that f(1,2,3) is executed when fr is invoked?

[UPDATE] I followed Jason Bunting's answer to here about the Partial Function and the JavaScript function he posts there is exactly what I was looking for. Here is the solution:

function partial(func /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments).splice(1);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(this, allArguments);
  };
}

Answer

Jason Bunting picture Jason Bunting · Dec 17, 2008

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.