Wolfgang Adamec
Wolfgang Adamec

Reputation: 8534

Context of JavaScript compare function of "sort"

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

Answers (2)

Denys Séguret
Denys Séguret

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

dan-lee
dan-lee

Reputation: 14502

You can do this by using bind:

this.models.sort(this.comparator.bind(context));

Upvotes: 2

Related Questions