Try the following:
a.map(Function.prototype.call.bind(String.prototype.trim ))
The reason this works, and just displaying String.prototype.trim does not work, because as others have pointed out, this will be undefined when a function tries to trim an array element. What this solution does is create a new function that takes this as the String.prototype.trim function. Since the new function is a modified version of Function.prototype.call , since map calls this function, passing it an array element, what essentially runs is: Function.prototype.call.call(String.prototype.trim, element) . This executes the String.prototype.trim function on the element passed in, and you get the result of the cutoff. This will also work:
a.map(Function.call, "".trim)
taking advantage of the fact that the second argument to map takes thisArg . For a little syntactic sugar, you can make a function that looks like this:
Array.prototype.mapUsingThis = function(fn) { return this.map(Function.call, fn); };
Then you can just call
a.mapUsingThis("".trim)
.
Hrishi
source share