When comparing
function(token) { return str.indexOf(token); }
to
str.indexOf
The main difference lies in the context problem that arises with the latter. In the second scenario, instead of str
, it would be window
. The expression str.indexOf
refers to the value of the property named indexOf
within the string object. While it is a function, there is no way to determine which object it is originated from based solely on this value. Therefore, passing str.indexOf
simply means passing the function itself, not a reference to str
.
["*", "^", "$"].map(str.indexOf);
is essentially the same as
["*", "^", "$"].map(function(token) { return window.indexOf(token); });
If an indexOf function existed in the global window scope.
To further clarify, although it's not recommended, a function can be bound to a specific object. For example, by using:
var f = str.indexOf.bind(str); // creates a copy of indexOf, bound to str
["*", "^", "$"].map(f);
the this
keyword inside f
will refer to str
when the function is invoked.