2

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

2 Answers 2

5

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);});
Sign up to request clarification or add additional context in comments.

1 Comment

@JanDvorak It starts at IE9.
2

You can do this by using bind:

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.