Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/" rel="noreferrer">bind</a> allows-</p> <ul> <li>set the value of "this" to an specific object. This becomes very helpful as sometimes <a href="http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/" rel="noreferrer">this</a> is not what is intended.</li> <li>reuse methods</li> <li>curry a function</li> </ul> <p>For example, you have a function to deduct monthly club fees</p> <pre><code>function getMonthlyFee(fee){ var remaining = this.total - fee; this.total = remaining; return this.name +' remaining balance:'+remaining; } </code></pre> <p>Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member. </p> <p>Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.</p> <pre><code>var rachel = {name:'Rachel Green', total:500}; </code></pre> <p>Now, create a function that can be used again and again to deduct the fee from her account every month</p> <pre><code>//bind var getRachelFee = getMonthlyFee.bind(rachel, 90); //deduct getRachelFee();//Rachel Green remaining balance:410 getRachelFee();//Rachel Green remaining balance:320 </code></pre> <p>Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25</p> <pre><code>var ross = {name:'Ross Geller', total:250}; //bind var getRossFee = getMonthlyFee.bind(ross, 25); //deduct getRossFee(); //Ross Geller remaining balance:225 getRossFee(); //Ross Geller remaining balance:200 </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