由于某种原因我无法使用String.prototype.trim.call
作为数组方法的回调,例如map
or 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
Demo: http://jsbin.com/ubUHiHon/1/edit?js,控制台 http://jsbin.com/ubUHiHon/1/edit?js,console
我假设在后一种情况下this
不指向数组元素,但我想清楚地解释正在发生的事情。
String.prototype.trim.call(string); // 'A'
array.map(String.prototype.trim.call); // TypeError: undefined is not a function
当您调用call
第一种情况下的方法,其this value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this绑定到String.prototype.trim
功能。在第二种情况下,您只需访问call
函数无需绑定到任何东西 - 你可以只使用
array.map(Function.prototype.call)
调用此方法时没有任何内容this
值、数组中的元素、索引和整个数组作为参数。你打电话时call
不是在函数上,它会抛出。您可以使用第二个参数map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map or the bind method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind修复this
的值call
:
array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)