Reputation: 8534
In my "class" method I use the JavaScript "sort" function plus a compare function:
this.models.sort(this.comparator);
When the sort function calls my comparator, is it possible to define the context/"this" for the comparator?
I know it can be done this way:
var self = this;
this.models.sort(function(a, b){return self.comparator.call(self, a, b);});
But does somebody know a simpler way?
Thanks alot in advance
Upvotes: 2
Views: 1191
Reputation: 382274
You can use bind :
this.models.sort(this.comparator.bind(this));
bind
builds a new bound function which will be executed with the context you pass.
As this isn't compatible with IE8, the closure solution is usually adopted. But you can make it simpler :
var self = this;
this.models.sort(function(a, b){return self.comparator(a, b);});
Upvotes: 5