rh said:
[...]
String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}
The FAQ version is clearly the correct way to trim strings. However,
I'm curious as to the reason the FAQ prototype is generated with "new
Function(str)" instead of the more common function-expression form
given above.
Strings introduce the requirement for double escaping the "\" (as per
new RegExp), and while such use may be instructive, it adds
chicken-track complexity where in a place where it doesn't appear to
be necessary.
Depends.
Am I missing some subletly regarding browser compatibility,
Yes, indeed you do. If Netscape's Core JavaScript Reference 1.5 and the
MSDN Library is to be trusted, the Function() constructor is available from
JavaScript 1.1 (NN3+) and JScript 2.0 (IE/IIS 3+) on, while the "function"
statement within another statement (including itself) or the "function"
operator (also defining anonymous functions) requires JavaScript 1.2 (NN4+)
or 1.5 (NN6+; in JScript AFAIS both are available in all versions and thus
all UAs), respectively. (Unfortunately, the Reference cannot be trusted
here since I had to learn that NN 4.7 which claims to support JavaScript
up to 1.3 only also supports the "function" operator.)
As for the ECMAScript standard, the "function" statement within a
statement is AFAIS not available before edition 3 as there is no
FunctionExpression to be produceable through the MemberExpression production.
While the UAs given respect to herewith may seem outdated, there may
be still UAs around which implement only those older versions of the
respective language(s). However, we also had one case of a buggy
implementation here that had b0rken Function() constructor support.
Google is your friend. [psf 6.1]
<
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/function.html#1193137>
<
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1004825>
<
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/ops.html#1066344>
or something to do with "this" association?
No.
String.prototype.trim = new Function(
"return this.match(/(\\b\\S+|\\S+)/g).join(' ');");
is semantically equal to the above.
HTH