Javascript Can';t使用字符串#trim作为数组#map的回调

Javascript Can';t使用字符串#trim作为数组#map的回调,javascript,string,prototype,Javascript,String,Prototype,由于某些原因,我不能使用String.prototype.trim.call作为数组方法的回调,例如map或filter 在这种情况下,两个功能的工作原理相同: function trim(string) { return string.trim(); } var string = ' A '; trim(string); // 'A' String.prototype.trim.call(string); // 'A' 但是,当我尝试将它们

由于某些原因,我不能使用
String.prototype.trim.call
作为数组方法的回调,例如
map
filter

在这种情况下,两个功能的工作原理相同:

function trim(string) {
  return string.trim();
}

var string = ' A ';

trim(string);                       // 'A'
String.prototype.trim.call(string); // 'A'
但是,当我尝试将它们作为数组方法的回调传递时,第二个方法失败:

var array = [' A', 'B ', ' C '];

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

我假设在后一种情况下,
这个
没有指向数组元素,但我想对发生的事情进行清楚的解释

在第一种情况下调用
call
方法时,其绑定到
String.prototype.trim
函数。在第二种情况下,您只需访问
调用
函数,而无需将其绑定到任何东西—您可以使用

array.map(Function.prototype.call)
调用此方法时,将不使用任何内容作为
This
值、数组中的元素、索引和整个数组作为参数。当您对函数调用
call
时,它会抛出。您可以使用的第二个参数或来修复调用的
值:

array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))

很抱歉,我已经回答了两次:)@Bergi看起来是的,很抱歉。但是,正如你所能想象的,几乎不可能找到一个(老实说,我花了15分钟)。我已经尝试使标题尽可能的笼统和准确。解决这个问题的一个优雅的方法是ES6 arrow函数:
array.map(s=>s.trim())。是的,当遇到这个问题时,我知道它是重复的,但找不到它。于是我写了一个答案,后来才发现原来的答案:——)
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))