Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'self = this' vs apply or bind? (Backbone)

Often in my Backbone code I come across situations where I would be passing a closure to some function and lose context of 'this'.

My solution for some time had been to do what I had seen some others do:

var self = this;

this.deferred.done(function () {
    self.render();
});

Or actually I switched to _this = this, but that's beside the point. It works, but it feels ugly and I sometimes have to do it quite often. So I'm trying to figure out a better way to do this. I learned I could do this:

this.deferred.done(function () {
    this.render();
}.apply(this));

And I think I could also use Underscore to do this:

this.deferred.done(_.bind(function () {
    self.render();
}, this));

The apply method seems the most succinct but I feel like it has a side effect (I just don't know what it is yet).

Edit:

Take a look at this JSbin where I use apply similar to as I mentioned: http://jsbin.com/qobumu/edit?js,console

It works, yet it throws an error at the same time. If I change the apply to bind, it works and doesn't throw an error.

like image 723
Kenmore Avatar asked Jul 20 '26 05:07

Kenmore


1 Answers

  • Function.bind is a native method, no need for underscore unless you're coding for antique browsers. Exactly what @dandavis said: this.deferred.done(this.render.bind(this)) (but note that bind can also bind function arguments, not just this)

  • if you're actually coding for cutting-edge browsers or node.js 4, you can use arrow functions which bind this lexically to whatever it is in the scope where the function is defined, so you could write: this.deferred.done(() => { this.render() });

like image 177
Touffy Avatar answered Jul 21 '26 17:07

Touffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!