不能使用String#trim作为Array#map的回调

Pav*_*vlo 8 javascript string prototype

出于某种原因,我不能String.prototype.trim.call用作数组方法的回调,例如mapfilter.

在这种情况下,两个函数的工作方式相同:

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

var string = ' A ';

trim(string);                       // 'A'
String.prototype.trim.call(string); // 'A'
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将它们作为数组方法的回调传递时,第二个失败:

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

array.map(trim);                       // ['A', 'B', 'C'];
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

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

我假设在后一种情况下this没有指向数组元素,但我想清楚地解释发生了什么.

Ber*_*rgi 9

String.prototype.trim.call(string); // 'A'
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

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

array.map(Function.prototype.call)
Run Code Online (Sandbox Code Playgroud)

调用此方法时不会将this值,数组中的元素,索引和整个数组作为参数调用.当你call不打电话给某个功能时,它会抛出.您可以使用第二个参数mapbind方法来修复以下thiscall:

array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))
Run Code Online (Sandbox Code Playgroud)