Cannot use String # trim as a callback for an Array # map

For some reason, I cannot use String.prototype.trim.call as a callback for array methods like map or filter .

In this case, the two functions work the same way:

 function trim(string) { return string.trim(); } var string = ' A '; trim(string); // 'A' String.prototype.trim.call(string); // 'A' 

However, when I try to pass them as a callback to an array method, the second one fails:

 var array = [' A', 'B ', ' C ']; array.map(trim); // ['A', 'B', 'C']; array.map(String.prototype.trim.call); // TypeError: undefined is not a function 

Demo: http://jsbin.com/ubUHiHon/1/edit?js,console

In the latter case, I assume that this does not point to an element of the array, but I would like to get a clear explanation of what is happening.

+8
javascript string prototype
source share
1 answer
 String.prototype.trim.call(string); // 'A' array.map(String.prototype.trim.call); // TypeError: undefined is not a function 

When you call the call method in the first case, its this value is bound to the String.prototype.trim function. In the second case, you simply call function without being attached to anything - you could just use

 array.map(Function.prototype.call) 

This method is called without anything like the value of this , an element from your array, index, and the entire array as parameters. When you call call not on a function, it throws. You can either use the second map parameter or the bind method to fix this value for call :

 array.map(Function.prototype.call, String.prototype.trim) array.map(Function.prototype.call.bind(String.prototype.trim)) 
+9
source share

All Articles