0

Are there advantages or differences to using _.bind versus using a local reference to this?

Here's a very simplified example: doAdd is an example of a local function that needs to effect a property on the parent object; it's ultimately run as a callback function inside doSomethingThenCallback. Option A vs. option B:

var obj = {
    num: 1,

    // Option A
    add_A: function() {
        function doAdd(){
            this.num++;
        }
        // Make the "this" in the function refer to the parent object
        doAdd = _.bind(doAdd, this);
        doSomethingThenCallback(doAdd);
    },

    // Option B
    add_B: function() {
        // Save a local reference to "this"
        var o = this;
        function doAdd(){
            o.num++;
        }
        doSomethingThenCallback(doAdd);
    }
}
Luke
  • 18,811
  • 16
  • 99
  • 115
  • if you need lexical this than bind it. it is better practice, it's cleaner and less prone to errors. if you need reference to both 'this' then assign it to variable. – webduvet Jul 31 '15 at 15:25
  • @webduvet Can you elaborate as an answer? Would be good to see what kind of errors it helps prevent. – Luke Jul 31 '15 at 15:28
  • 1
    Your `_.bind(doAdd, this)` does nothing useful, `_.bind` returns the bound function, it doesn't modify it in-place. – mu is too short Jul 31 '15 at 17:17
  • See http://stackoverflow.com/questions/6397096/function-bind-vs-closure-in-javascript-how-to-choose. –  Jul 31 '15 at 18:22
  • @muistooshort Thanks. I made an edit to correct that. – Luke Jul 31 '15 at 21:13
  • 1
    You left out an option that seems to be fairly common these days: you can provide a second context argument to `doSomethingThenCallback` so that it can call the callback with whatever `this` you need using [`Function.prototype.apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). The choice is mostly a matter of personal taste, cases where it matters are fairly rare. – mu is too short Jul 31 '15 at 21:36

0 Answers0