Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does call does not work as A sort function?

Tags:

javascript

v8

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?

like image 272
Leon Fedotov Avatar asked Mar 08 '26 23:03

Leon Fedotov


1 Answers

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.

like image 90
icktoofay Avatar answered Mar 10 '26 14:03

icktoofay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!