[英]difference between String.prototype.trim.call(text) and text.trim()
Looking into jQuery's source: 看看jQuery的来源:
// Use native String.trim function wherever possible
trim: trim && !trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
is there a reason Why they use trim.call(text) instead of text.trim()? 有什么理由为什么他们使用trim.call(text)而不是text.trim()? Thanks a lot!!
非常感谢!!
UPDATE: 更新:
Right this way it won't throw exceptions if the argument is not a string. 这样,如果参数不是字符串,它将不会抛出异常。 But according to jQuery's doc, the argument is supposed to be a string so if user uses it wrong, should it throw an exception (otherwise user might not notice what's wrong)?
但根据jQuery的doc,该参数应该是一个字符串,所以如果用户使用它错了,它应该抛出异常(否则用户可能不会注意到什么是错的)?
And to Nathaniel Currier: the mothod is jQuery.trim() not jQuery.fn.trim() so it is not chained. 而Nathaniel Currier:mothod是jQuery.trim()而不是jQuery.fn.trim()所以它没有链接。
I'm not sure that this was their design rationale, but using call()
will work with objects that are not strings: 我不确定这是他们的设计原理,但使用
call()
将使用非字符串的对象:
var a = [1, 2, 3];
var b = String.prototype.trim.call(a); // same result as b = '1,2,3'
var c = a.trim(); // => generates TypeError
Notice that their polyfill coerces text
to a string with ( text + "" )
. 请注意,他们的polyfill将
text
强制转换为带有( text + "" )
的字符串。
String.trim() is not available in all (older) browsers so they use native if available (as its faster) or their own implementation if not... String.trim()并非在所有(较旧的)浏览器中都可用,因此如果不可用,它们将使用本机(如果更快)或者它们自己的实现,如果不是......
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
also see this for information about how Function.prototype.call() behaves https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call 还可以看到这个有关Function.prototype.call()行为的信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
当text
不是字符串时, text.trim()
将抛出错误( TypeError: .... has no method 'trim'
),而String.prototype.trim.call(text)
则不会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.