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?
callneeds to be bound tolocaleCompare:The reason you are having a problem is that you are passing
sortFunction.prototype.call. As you may know, when nothisis otherwise provided, it will be the global object (windowin browser environments). Thus, whensorttries to call the function passed to it, it will be callingcallwiththisset to the global object, which in most (all?) cases is not a function. Therefore, you must bindcallsothisis alwayslocaleCompare.