函数调用方法作为回调


如果我

错过了什么,请原谅我,但是当我尝试使用调用方法作为回调时,它在Chrome和Node.js中都给了我奇怪的错误。

['  foo', ' bar  '].map(String.prototype.trim.call);
TypeError: ["  foo", " bar  "].map is not a function
at Array.map (native)

但是这些片段有效:

['  foo', ' bar  '].map(function (item) { 
    return String.prototype.trim.call(item);
}); // => ['foo', 'bar']
/*
  and ES2015
*/
['  foo', ' bar  '].map(function () { 
    return String.prototype.trim.call(...arguments);
}); // => ['foo', 'bar']

我还检查了call函数的类型:

typeof String.prototype.trim.call; // => 'function'

我做错了什么吗?谁能解释一下为什么我得到这样的错误?谢谢。

最简单的

解决方案是把它写出来:

['  foo', ' bar  '].map(s => s.trim());

如果你想传递一个函数,你将需要一些比你想要的更复杂的东西,就像

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

或者如果你愿意

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

这个问题可以回答你所有的问题。