Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Bind creates a new function that will have <code>this</code> set to the first parameter passed to <code>bind()</code>.</p> <p>Here's an example that shows how to use <code>bind</code> to pass a member method around that has the correct <code>this</code>:</p> <pre><code>var Button = function(content) { this.content = content; }; Button.prototype.click = function() { console.log(this.content + ' clicked'); }; var myButton = new Button('OK'); myButton.click(); var looseClick = myButton.click; looseClick(); // not bound, 'this' is not myButton - it is the global object var boundClick = myButton.click.bind(myButton); boundClick(); // bound, 'this' is myButton </code></pre> <p>Which prints out:</p> <pre><code>OK clicked undefined clicked OK clicked </code></pre> <p>You can also add extra parameters after the 1st (<code>this</code>) parameter and <code>bind</code> will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:</p> <pre><code>// Example showing binding some parameters var sum = function(a, b) { return a + b; }; var add5 = sum.bind(null, 5); console.log(add5(10)); </code></pre> <p>Which prints out:</p> <pre><code>15 </code></pre> <p>Check out <a href="http://www.javascripture.com/Function#bind" rel="noreferrer">JavaScript Function bind</a> for more info and interactive examples.</p> <p>Update: ECMAScript 2015 adds support for <code>=&gt;</code> functions. <code>=&gt;</code> functions are more compact and do not change the <code>this</code> pointer from their defining scope, so you may not need to use <code>bind()</code> as often. For example, if you wanted a function on <code>Button</code> from the first example to hook up the <code>click</code> callback to a DOM event, the following are all valid ways of doing that:</p> <pre><code>Button.prototype.hookEvent(element) { // Use bind() to ensure 'this' is the 'this' inside click() element.addEventListener('click', this.click.bind(this)); }; </code></pre> <p>Or: </p> <pre><code>Button.prototype.hookEvent(element) { // Use a new variable for 'this' since 'this' inside the function // will not be the 'this' inside hookEvent() var me = this; element.addEventListener('click', function() { me.click() }); } </code></pre> <p>Or:</p> <pre><code>Button.prototype.hookEvent(element) { // =&gt; functions do not change 'this', so you can use it directly element.addEventListener('click', () =&gt; this.click()); } </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