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);
}
}