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);
};
}