Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use <code>.bind()</code> when you want that function to later be called with a certain context, useful in events. Use <code>.call()</code> or <code>.apply()</code> when you want to invoke the function immediately, and modify the context.</p> <p>Call/apply call the function immediately, whereas <code>bind</code> returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.</p> <p>I do this a lot:</p> <pre><code>function MyObject(element) { this.elm = element; element.addEventListener('click', this.onClick.bind(this), false); }; MyObject.prototype.onClick = function(e) { var t=this; //do something with [t]... //without bind the context of this function wouldn't be a MyObject //instance as you would normally expect. }; </code></pre> <p>I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.</p> <p>A simple, naive implementation of bind would be like:</p> <pre><code>Function.prototype.bind = function(ctx) { var fn = this; return function() { fn.apply(ctx, arguments); }; }; </code></pre> <p>There is more to it (like passing other args), but you can read more about it and see the real implementation <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" rel="noreferrer">on the MDN</a>.</p> <p>Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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