HTML and CSS Reference
In-Depth Information
statments as a syntax extension. Syntax extensions are legal in the spec, but not
something to rely on.
The only difference between the function expressions and function declara-
tions above is that the functions created with declarations have names. These
names are useful both to call functions recursively, and even more so in debug-
ging situations. Let's rephrase the trim method and rather define it directly on the
String.prototype object for the browsers that lack it. Listing 5.20 shows an
updated example.
Listing 5.20 Conditionally providing a string method
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+ | \s+ $ /g, "");
With this formulation we can always trim strings using " string ".trim()
regardless of whether the browser supports the method natively. If we build a large
application by defining methods like this, we will have trouble debugging it, because,
e.g., Firebug stack traces will show a bunch of calls to anonymous functions, making
it hard to navigate and use to locate the source of errors. Unit tests usually should
have our backs, but readable stack traces are valuable at any rate.
Named function expressions solve this problem, as Listing 5.21 shows.
Listing 5.21 Using a named function expression
if (!String.prototype.trim) {
String.prototype.trim = function trim() {
return this.replace(/^\s+ | \s+ $ /g, "");
Named function expressions differ somewhat from function declarations; the
identifier belongs to the inner scope, and should not be visible in the defining scope.
Unfortunately, Internet Explorer does not respect this. In fact, Internet Explorer
does not do well with named function expressions at all, as side effects of the above
example show in Listing 5.22.
Listing 5.22 Named function expressions in Internet Explorer
// Should throw a ReferenceError, true in IE
Search WWH ::

Custom Search