Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I pass a reference to a function, with parameters?
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/321113/how-can-i-pre-set-arguments-in-javascript-function-call-partial-function-appli">How can I pre-set arguments in JavaScript function call? (Partial Function Application)</a> </p> </blockquote> <p>I need to able to <strong>pass a reference to a function with a given set of parameters</strong>.</p> <p>Here is an example of passing a reference <strong><em>without</strong> parameters</em>:</p> <pre><code>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 </code></pre> <p>Now what I need to do is pass the same <code>f</code> 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 <code>f</code> function with parameters inside the newly created function, like such:</p> <pre><code>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 </code></pre> <p>But my question is, <strong>Is there a way to pass a direct reference to the <code>f</code> function With parameters to <code>fr</code>, but without enclosing it in an anonymous function?</strong></p> <p><em>What do I need to assign to <code>fr</code> to make it invokable without parameters (<code>fr()</code>), so that f(1,2,3) is executed when <code>fr</code> is invoked?</em> </p> <p><strong>[UPDATE]</strong> I followed <a href="https://stackoverflow.com/questions/373157/javascript-passing-a-reference-to-a-function-with-parameters#373216">Jason Bunting</a>'s answer to <a href="https://stackoverflow.com/questions/321113">here</a> about the <em>Partial Function</em> and the JavaScript function he posts there is exactly what I was looking for. Here is the solution:</p> <pre><code>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); }; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload