Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, this is certainly possible. <code>apply</code> returns the result of a function, so it's not applicable here, however, <code>bind</code> fits.</p> <p>You may wish to read the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind?redirectlocale=en-US&amp;redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fbind" rel="nofollow">MDN docs for Bind</a>.</p> <p>Since bind works in order, if you alter the order of your parameters this is nice and elegant. Let's change the signature of <code>sortby</code> to: <code>function sortby(prop, a, b) {</code>. Now we can easily tell bind to fix the first parameter:</p> <pre><code>someArray.sort(sortby.bind(undefined, 'propertyname')); </code></pre> <p>Note the <code>undefined</code>. The first parameter to <code>bind</code> (as per the docs) is a new <code>this</code> reference. Since we don't use it, we'll pass <code>undefined</code> to say that we don't want to change the context. The next parameter tells bind to create a function which passes a value of 'propertyname' as the first argument to <code>sortby</code>. This gives us a <em>partial function application</em>; returning a function which takes two parameters, calling <code>sortby</code> with the first value that we've already given it, then the two parameters. This function is passed to <code>sort</code>, calling it as it needs.</p> <p>Manually interpreting the call to bind, it gives you something like this:</p> <pre><code>someArray.sort(function (a, b) { sortby.apply(this, 'propertyname', a, b); }); </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