I'm reading javascript the good parts, and the author gives an example that goes like so:
['d','c','b','a'].sort(function(a,b) {
return a.localeCompare(b);
});
Which behaves as expected. Now I have tried to do something like this - which is the next logical step:
['d','c','b','a'].sort(String.prototype.localeCompare.call);
And that fails with an error:
TypeError: object is not a function
Now I left wondering why... Any ideas?
call needs to be bound to localeCompare:
['d','c','b','a'].sort(Function.prototype.call.bind(String.prototype.localeCompare));
The reason you are having a problem is that you are passing sort Function.prototype.call. As you may know, when no this is otherwise provided, it will be the global object (window in browser environments). Thus, when sort tries to call the function passed to it, it will be calling call with this set to the global object, which in most (all?) cases is not a function. Therefore, you must bind call so this is always localeCompare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With