Why can’t I do the following?
var str = "A string with * and ^ and even $";
var indeces = ["*", "^", "$"].map(str.indexOf); // doesnt work
I’d rather not pass in another function to do the exact same thing as the method itself…
[...].map(function(token) { return str.indexOf(token); }); // works
Is there an elegant way to do this?
The difference between
and
is that you wouldn’t have context problem in the first case.
In the second case, this would no be
strbutwindow.str.indexOfis the value of the property namedindexOfof the string. It’s a function but there is no way from the value to know from which object you took it. So if you passstr.indexOf, you’re just passing the function, not at allstr.would be equivalent to
if there was a indexOf function on window.
Just to try to be clearer, but don’t use it : a function could be bound to an object. If you do
then
thisisstrwhenfis called.