Pav*_*vlo 8 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'
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
没有指向数组元素,但我想清楚地解释发生了什么.
Run Code Online (Sandbox Code Playgroud)String.prototype.trim.call(string); // 'A' array.map(String.prototype.trim.call); // TypeError: undefined is not a function
call
在第一种情况下调用方法时,其this
值将绑定到String.prototype.trim
函数.在第二种情况下,您只需访问该call
函数而不必将其绑定到任何东西 - 您可以使用它
array.map(Function.prototype.call)
Run Code Online (Sandbox Code Playgroud)
调用此方法时不会将this
值,数组中的元素,索引和整个数组作为参数调用.当你call
不打电话给某个功能时,它会抛出.您可以使用第二个参数map
或bind
方法来修复以下this
值call
:
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))
Run Code Online (Sandbox Code Playgroud)