How come
var a = "foo / bar/ baz ".split('/');
a.map( function (e) { return String.prototype.trim.call(e) } )
works, while this doesn't...
a.map( String.prototype.trim );
How come
var a = "foo / bar/ baz ".split('/');
a.map( function (e) { return String.prototype.trim.call(e) } )
works, while this doesn't...
a.map( String.prototype.trim );
Try this:
The reason why this works and just mapping
String.prototype.trim
doesn't work is because, as others have pointed out, thethis
will be undefined when the function tries to trim the array element. What this solution does is, it creates a new function, which takes as it'sthis
value as the functionString.prototype.trim
. Since the new function is a modified version ofFunction.prototype.call
, asmap
calls this function passing it the array element, what essentially gets executed is:Function.prototype.call.call(String.prototype.trim, element)
. This runs the functionString.prototype.trim
on the element passed in and you get the trimmed result. This also would work:by taking advantage of the fact that the second argument to
map
accepts thethisArg
. For a little bit of syntactic sugar, you can make a function that looks like this:Then, you could just invoke
like that.
'this'
refers to the string param in the first case whereas in the second case, 'this' becomes undefined asString.prototype.trim
is not bound to any object.String.prototype.trim is a non params function, it will be called by string itself, but map function need a func arg accept a str as params