Looking into jQuery's source:
// 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()? 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)?
And to Nathaniel Currier: the mothod is jQuery.trim() not jQuery.fn.trim() so it is not chained.
I'm not sure that this was their design rationale, but using call()
will work with objects that are not strings:
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 + "" )
.
String.trim() is not available in all (older) browsers so they use native if available (as its faster) or their own implementation if not...
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
当text
不是字符串时, text.trim()
将抛出错误( TypeError: .... has no method 'trim'
),而String.prototype.trim.call(text)
则不会。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.